我有3张桌子
orders
-----------------
| id | order_data |
-----------------
codes
-----------------------------
| id | code_data | order_id |
-----------------------------
actions (please note, in the table the primary key doesn't exists)
--------------------------
| action_name | order_id |
--------------------------
如果操作行在表actions
中没有唯一值,那么我可以按顺序计算操作数,因此DISTINCT
中的COUNT()
没有意义。
我的问题:
SELECT `orders`.*, COUNT(DISTINCT `codes`.`id`), COUNT(`actions`.`action_name`)
FROM `orders`
LEFT JOIN `codes` ON `codes`.`id` = `orders`.`id`
LEFT JOIN `actions` ON `actions`.`id` = `orders`.`id`
WHERE `actions`.`action_name` IN (/*some values*/)
GROUP BY `orders`.`id`
答案 0 :(得分:0)
SELECT orders.*
, COUNT(DISTINCT c.id)
, COUNT(a.action_name)
FROM orders o
LEFT
JOIN codes c
ON c.id = o.id
LEFT
JOIN actions a
ON a.id = o.id
AND a.action_name IN (/*some values*/)
GROUP
BY o.id
答案 1 :(得分:0)
在加入之前计算其他表格,如下所示:
SELECT
`orders`.*
, IFNULL(a.CountActs, 0) CountActs
, IFNULL(c.CountCodes, 0) CountCodes
FROM `orders`
LEFT JOIN (
SELECT `order_id`, count(*) CountCodes
FROM `codes`
GROUP BY `order_id`
) c ON `orders`.`id` = c.`order_id`
LEFT JOIN (
SELECT `order_id`, count(*) CountActs
FROM `actions`
WHERE `actions`.`action_name` IN (/*some values*/)
GROUP BY `order_id`
) a ON `orders`.`id` = a.`order_id`