[英]MySQL: why is a query using a VIEW less efficient compared to a query directly using the view's underlying JOIN?
[英]Why does MySQL View and the same View's underlying SELECT query return different results?
我可以在此問題上提供一些幫助,在此問題中,我試圖生成一組結果,將余額提前並結轉余額。
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 時,我得到了這個(錯誤的結果):
當我運行用於創建 VIEW 的完整 SELECT 語句時,我得到了這個(正確的結果):
提前致謝。
您發布的查詢甚至不應該工作。
year
東西year(
tx .
date_created ) < year
也不應該工作除此之外,您不必多次執行基本相同的查詢。 您可以將查詢縮短為如下所示:
SELECT `th`.`user_id` AS usrid
, year(`th`.`date_created`) AS 'year'
sum(if(year(td.date_created`) < year, amount, 0)) as bal_ytd,
sum(if(year(td.date_created`) <= year, amount, 0)) as 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`)
(當然,這個奇怪的year
對你有用)
以下腳本已正常工作。 感謝所有幫助和提示:
CREATE OR REPLACE VIEW vwbalances AS
SELECT tho.user_id AS usrid, YEAR(td.date_created) AS 'year'
, ROUND(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 = tho.user_id AND
YEAR(tx.date_created) < YEAR(td.date_created) ),0),2) AS
bal_bfwd
, round(sum(td.amount),2) AS bal_ytd
, ROUND(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 = tho.user_id AND
YEAR(ty.date_created) <= YEAR(td.date_created)),0),2) AS
bal_cfwd
FROM transdetail td JOIN transhdr tho ON tho.thdr_id =
td.thdr_id
JOIN users u ON tho.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 tho.user_id, YEAR(td.date_created);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.