問題描述
我一直在獲取連接表上的 SUM 時(shí)遇到問題,總是有問題,我可以通過運(yùn)行兩個(gè)查詢來獲得我需要的結(jié)果,我想知道這兩個(gè)查詢是否可以組合成一個(gè)連接查詢,這里是我的查詢以及我加入查詢的嘗試
I have always had trouble getting SUMs on join tables, there is always an issue, I can get the results I need by running two queries, I am wondering if this two queries can be combine to make one join query, here is the queries I have and my attempt to join the query
查詢 1
SELECT last_name, first_name, DATE_FORMAT( (mil_date), '%m/%d/%y' ) AS dates,
SUM( drive_time ) MINUTES FROM bhds_mileage LEFT JOIN bhds_teachers i
ON i.ds_id = bhds_mileage.ds_id
WHERE mil_date BETWEEN '2016-04-11' AND '2016-04-30'
AND bhds_mileage.ds_id =5
GROUP BY CONCAT( YEAR( mil_date ) , '/', WEEK( mil_date ) ) ,
bhds_mileage.ds_id
ORDER BY last_name ASC , dates ASC
以分鐘為單位的輸出是271,281,279
the output in minutes is 271, 281, 279
查詢 2
SELECT last_name, first_name, DATE_FORMAT((tm_date), '%m/%d/%y') AS dates,
SUM(tm_hours) total FROM bhds_timecard LEFT JOIN bhds_teachers i
ON i.ds_id = bhds_timecard.ds_id
WHERE tm_date BETWEEN '2016-04-11' AND '2016-04-30' AND bhds_timecard.ds_id = 5
GROUP BY CONCAT(YEAR(tm_date), '/', WEEK(tm_date)), bhds_timecard.ds_id
ORDER BY last_name ASC, dates ASC
這里的輸出是 33.00, 36.00, 26.75
The output here is 33.00, 36.00, 26.75
現(xiàn)在我嘗試加入查詢
SELECT last_name, first_name, DATE_FORMAT((tm_date), '%m/%d/%y') AS dates,
SUM(tm_hours) total, SUM( drive_time ) MINUTES FROM bhds_timecard
LEFT JOIN bhds_teachers i ON i.ds_id = bhds_timecard.ds_id
LEFT JOIN bhds_mileage ON DATE_FORMAT((bhds_timecard.tm_date), '%m/%d/%y') =
DATE_FORMAT((bhds_mileage.mil_date), '%m/%d/%y') AND bhds_timecard.ds_id = bhds_mileage.ds_id
WHERE tm_date BETWEEN '2016-04-11' AND '2016-04-30' AND bhds_timecard.ds_id = 5
GROUP BY CONCAT(YEAR(tm_date), '/', WEEK(tm_date)), bhds_timecard.ds_id
括號(hào)是預(yù)期的
輸出 1044 (271), 1086 (281), 1215 (279)
this outputs 1044 (271), 1086 (281), 1215 (279)
推薦答案
當(dāng)您在主查詢中使用多個(gè)連接時(shí),您最終會(huì)得到所有表的叉積,因此總和乘以匹配的行數(shù)在另一張桌子上.您需要將總和移動(dòng)到子查詢中.
When you use multiple joins in the main query, you end up with a cross product of all the tables, so the sums get multiplied by the number of rows matching in another table. You need to move the sums into subqueries.
SELECT last_name, first_name, DATE_FORMAT(LEAST(mil_date, tm_date), '%m/%d/%y' ) AS dates,
total, minutes
FROM bhds_teachers AS i
LEFT JOIN (
SELECT ds_id, YEARWEEK(mil_date) AS week, MIN(mil_date) AS mil_date, SUM(drive_time) AS minutes
FROM bhds_mileage
WHERE mil_date BETWEEN '2016-04-11' AND '2016-04-30'
AND bhds_mileage.ds_id = 5
GROUP BY ds_id, week) AS m
ON m.ds_id = i.ds_id
LEFT JOIN (
SELECT ds_id, YEARWEEK(tm_date) AS week, MIN(tm_date) AS tm_date, SUM(tm_hours) AS total
WHERE tm_date BETWEEN '2016-04-11' AND '2016-04-30' AND bhds_timecard.ds_id = 5
GROUP BY ds_id, week) AS t
ON t.ds_id = i.ds_id AND t.week = m.week
這篇關(guān)于在 MYSQL 中加入帶有 SUM 問題的表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!