我想问一个关于mysql查询的快速问题。
我有一个名为trans的表:
+----+---------------------+------+-------+----------+----------+
| ID | Date | User | PCNum | Customer | trans_In |
+----+---------------------+------+-------+----------+----------+
| 8 | 2013-01-23 16:24:10 | test | PC2 | George | 10 |
| 9 | 2013-01-23 16:27:22 | test | PC2 | Nick | 0 |
| 10 | 2013-01-24 16:28:48 | test | PC2 | Ted | 10 |
| 11 | 2013-01-25 16:36:40 | test | PC2 | Danny | 10 |
+----+---------------------+------+-------+----------+----------+
和其他指定客户:
+----+---------+-----------+
| ID | Name | Surname |
+----+---------+-----------+
| 1 | George | |
| 2 | Nick | |
| 3 | Ted | |
| 4 | Danny | |
| 5 | Alex | |
| 6 | Mike | |
.
.
.
.
+----+---------+-----------+
我想查看日期范围内特定客户的trans_in列的总和,但也包括在结果集中,那些在所选日期范围内没有任何记录的客户。它们的trans_in总和可能显示为NULL或0并不重要......
我有以下查询:
SELECT
`Date`,
Customer,
SUM(trans_in) AS 'input'
FROM trans
WHERE Customer IN('George','Nick','Ted','Danny')
AND `Date` >= '2013-01-24'
GROUP BY Customer
ORDER BY input DESC;
但这只会返回'Ted'和'Danny'的总和,因为它们只在1月24日之后才有交易......
如何包含WHERE IN(...)函数内的所有客户,即使是那些在所选日期范围内没有交易的客户?
我想我必须以某种方式加入他们与客户表,但我无法弄清楚如何。
提前致谢!!
:)
答案 0 :(得分:2)
为了包含一个表中的所有记录而不在另一个表中匹配记录,您必须使用LEFT JOIN。
SELECT
t.`Date`,
c.name,
SUM(t.trans_in) AS 'input'
FROM customers c LEFT JOIN trans t ON (c.name = t.Customer AND t.`Date` >= '2013-01-24')
WHERE c.name IN('George','Nick','Ted','Danny')
GROUP BY c.name
ORDER BY input DESC;
当然,我要提到您应该按ID引用客户,而不是相关表中的名称。您当前的设置会导致信息重复。如果客户更改了其名称,您现在必须更新转换表中的所有相关记录,而不是仅更新客户表中的记录。
答案 1 :(得分:0)
试试这个
SELECT
`Date`,
Customer,
SUM(trans_in) AS 'input'
FROM trans
inner join customers
on customers.Name = trans.Customer
WHERE Customer IN('George','Nick','Ted','Danny')
GROUP BY Customer
ORDER BY input DESC;