我有以下疑问 -
SELECT COUNT(capture_id) as count_captures
FROM captures
WHERE user_id = 9
...返回5
SELECT COUNT(id) as count_items
FROM items
WHERE creator_user_id = 9
...返回22
我尝试了以下查询 -
SELECT COUNT(capture_id) as count_captures,
COUNT(items.id) as count_items
FROM captures
LEFT JOIN items ON captures.user_id = items.creator_user_id
WHERE user_id = 9
...但它返回两列,其中110为值。我想要一列5列,另一列22块。我做错了什么?
答案 0 :(得分:3)
我的下意识是一个子查询:
select count(capture_id) as count_captures,
(select count(id) as count_items
from items i where i.creator_user_id = captures.user_id) as count_items
from captures
where user_id = 9
我不确定你能做些什么来避免这种情况。你看到了预期的(通常是期望的行为)。
当然,如果你知道两者中的ID都不会重复,你可以使用distinct:
SELECT COUNT( DISTINCT capture_id) as count_captures,
COUNT( DISTINCT items.id) as count_items
FROM captures
LEFT JOIN items ON captures.user_id = items.creator_user_id
WHERE user_id = 9
答案 1 :(得分:2)
LEFT JOIN返回左表中的每一行,右表中的每一行都与结果匹配。因为你的所有id都是相同的,它产生了表的笛卡尔积。 (5 * 22 = 110)。
预计会发生这种情况。
答案 2 :(得分:1)
您可以随时结合结果(警告,未经测试):
SELECT SUM(sub.count_captures), SUM(sub.count_items)
FROM (SELECT COUNT(capture_id) as count_captures, 0 as count_items
from captures where user_id = 9
UNION
SELECT 0 as count_captures, count(id) as count_items
from items where creator_user = 9) sub
答案 3 :(得分:1)
将两个(看似不相关的)查询合并为一个的另一种方法:
SELECT
( SELECT COUNT(capture_id)
FROM captures
WHERE user_id = 9
)
AS count_captures
, ( SELECT COUNT(id)
FROM items
WHERE creator_user_id = 9
)
AS count_items
在这些情况下,确实不需要子查询或JOIN。虽然优化器可能足够聪明,但我不会试图混淆他。