为什么MySQL View和同一View的基础SELECT查询返回不同的结果?

问题描述 投票:-2回答:1

我可以在此问题上提供一些帮助,在该问题中,我试图生成一组结转余额和结转余额的结果。

MySQL脚本:

CREATE OR REPLACE VIEW vwbalances AS
SELECT th.user_id usrid
     , YEAR(th.date_created) year 
     , IFNULL(
              (SELECT SUM(tx.amount) 
                 FROM transdetail tx 
                 JOIN transhdr th 
                   ON th.thdr_id = tx.thdr_id
                 JOIN users u 
                   ON th.user_id = u.user_id 
                 JOIN transtype tt 
                   ON tt.ttype_id = tx.ttype_id 
                WHERE tx.ttype_id in (2,9,11) 
                  AND u.user_id = usrid 
                  and YEAR(tx.date_created) < year
              )
           ,0) bal_bfwd
     , SUM(td.amount) bal_ytd
     , ifnull(
              (SELECT SUM(ty.amount) 
                 FROM transdetail ty 
                 JOIN transhdr th
                   ON th.thdr_id = ty.thdr_id
                 JOIN users u 
                   ON th.user_id = u.user_id 
                 JOIN transtype tt 
                   ON tt.ttype_id = ty.ttype_id 
                WHERE ty.ttype_id in (2,9,11) 
                  AND u.user_id = usrid 
                  AND YEAR(ty.date_created) <= year
              )
           ,0) bal_cfwd
  FROM transdetail td 
  JOIN transhdr th 
    ON th.thdr_id = td.thdr_id
  JOIN users u 
    ON th.user_id = u.user_id 
  JOIN transtype tt 
    ON tt.ttype_id = td.ttype_id 
 WHERE td.ttype_id in (2,9,11) 
 GROUP 
    BY th.user_id
     , YEAR(th.date_created)

当我运行SELECT * FROM vwbalances时得到这个(错误的结果):>

WRONG Results from the View:

并且当我运行用于创建VIEW的完整SELECT语句时,我得到了这个(正确的结果):

CORRECT Results from the underlying Select statement

提前感谢。

我可以在此问题上提供一些帮助,在该问题中,我试图通过结转余额和结转余额来生成一组结果。 MySQL脚本:CREATE OR REPLACE VIEW ...

mysql sql view
1个回答
1
投票

0
投票

您发布的查询甚至不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.