我基本上有一個表,其中包含每個日期的計數。我想創建一個查詢,該查詢給出了整個表上的計數總數,以及昨天的總數。但是當我嘗試加入表格兩次時,聚合關閉。以下是您可以如何複製結果。mysql當我連接兩次表相同的表聚合是錯誤的
CREATE TABLE a (id int primary key);
CREATE TABLE b (a_id int, b_id int, date date, count int, primary key (a_id,b_id,date));
INSERT INTO a VALUES (1);
INSERT INTO b VALUES (1, 1, UTC_DATE(), 5);
INSERT INTO b VALUES (1, 2, UTC_DATE(), 10);
INSERT INTO b VALUES (1, 1, UTC_DATE()-1, 7);
INSERT INTO b VALUES (1, 2, UTC_DATE()-1, 12);
SELECT A.id,SUM(B.count) AS total_count,SUM(Y.count) AS y FROM a AS A
LEFT JOIN b AS B ON (B.a_id=A.id)
LEFT JOIN b AS Y ON (Y.a_id=A.id AND Y.date=UTC_DATE()-1)
GROUP BY A.id;
Results in:
+----+-------------+------+
| id | total_count | y |
+----+-------------+------+
| 1 | 68 | 76 |
+----+-------------+------+
The correct result should be:
+----+-------------+------+
| id | total_count | y |
+----+-------------+------+
| 1 | 34 | 22 |
+----+-------------+------+
這是怎麼回事?這是一個在MySQL中的錯誤,或者我不理解連接如何工作。
謝謝,首先我介紹了mysql IF語句。這是最後工作的查詢:SELECT a.id,SUM(b.count)AS total_count,SUM(IF(b.date = UTC_DATE() - 1,b.count,0))FROM aa LEFT JOIN bb ON (b.a_id = a.id)GROUP BY a.id; –