我在下面有一些特定的数据库表格:
用户表
+----------+
|id| name |
+--+-------+
|1 | Mr. A |
|2 | Mr. B |
|3 | Mr. C |
+--+-------+
类别项目
+--+-------+
|id| name |
+--+-------+
|1 | Cat 1 |
|2 | Cat 2 |
|3 | Cat 3 |
+--+-------+
项目表
+---+-------------+--------+-------+
|id | category_id | title | price |
+---+-------------+--------+-------+
|1 |1 | title 1|10 |
|2 |1 | title 2|5 |
|3 |1 | title 3|20 |
|4 |2 | title 4|10 |
|5 |2 | title 5|15 |
|6 |3 | title 6|30 |
+---+-------------+--------+-------+
交易表
+---+--------+--------+---------+------------+----------+
|id | user_id| item_id|buy_value|buy_at_price| date |
+---+--------+--------+---------+------------+----------+
|1 |1 | 1 |5 |10 |2018-01-01|
|2 |1 | 3 |2 |20 |2018-01-01|
|3 |1 | 3 |1 |20 |2018-01-01|
|4 |2 | 4 |2 |10 |2018-01-01|
|5 |2 | 5 |2 |15 |2018-01-02|
+---+--------+--------+---------+------------+----------+
帮我执行一个mysql查询,可以按类别进行每日销售回顾。这种概述的例子产生了这样的表格(如果在2018-01-01重述)。
查询结果应为:
+-------------+--------------+--------------------------+-----------------+
| category_id | category_name| total_category_buy_value |category_income |
+-------------+--------------+--------------------------+-----------------+
|1 | Cat 1 |8 |110 |
|2 | Cat 2 |2 |20 |
|3 | Cat 3 |0 |0 |
+---+-------------+----------+--------------------------+-----------------+
但是,我的查询未显示 Cat 3 。 这是我的查询
SELECT
category.id AS category_id,
category. NAME AS category_name,
sum(`transaction`.buy_value) AS total_category_buy_value,
sum(
`transaction`.buy_value * `transaction`.buy_at_price
) AS total_income
FROM
category
JOIN item ON item.category_id = category.id
JOIN `transaction` ON `transaction`.item_id = item.id
WHERE
`transaction`.date LIKE '2018-01-01%'
GROUP BY
category_id
请访问http://sqlfiddle.com/#!9/ce4b1/1/0
谢谢
答案 0 :(得分:1)
要获取所有类别,无论是交易(通过项目)还是没有任何交易数据,您都可以使用LEFT
加入项目和交易表。
SELECT
c.id AS category_id,
c.name AS category_name,
COALESCE(SUM(t.buy_value),0) AS total_category_buy_value,
COALESCE(SUM(t.buy_value * t.buy_at_price),0) AS total_income
FROM
category c
LEFT JOIN item i ON i.category_id = c.id
LEFT JOIN `transaction` t ON t.item_id = i.id
AND t.date LIKE '2018-01-01%'
GROUP BY c.id,c.name
在上面你还可以注意到我已经从ON
移动了WHERE
子句中的日期过滤器,因此不会将整个事务表加入到与此过滤器匹配的数据上,如果你在WHERE
中使用此子句,它将转换内连接中的外连接