我有两个表,想要在两个表中计算一个ID号。一个表只有一个结果,但另一个表可能有更多结果。
select
a.ID,
count(a.ID),
count(b.ID)
from a
join b on
(b.ID=a.ID)
where a.ID='7820193'
group by a.ID
结果看起来像这样 ID 7820193 count(a.ID)= 200 计数(b.ID)= 200
但是,a中只有一个该ID号的实例 我试过所有类型的连接(左,右,内) 我做错了什么?
答案 0 :(得分:0)
这应该可以解决问题:
SELECT
Derived.id,
COUNT(*),
Derived.count
FROM(
SELECT
id,
COUNT(*) AS count
FROM a
WHERE id = 7820193
) AS Derived
JOIN b AS b ON b.id = Derived.id
答案 1 :(得分:0)
select
a.id,
count(a.id),
b.id,
count(b.id)
from a,b
where a.id = b.id and a.id = ''7820193'
group by
a.id,
b.id;
答案 2 :(得分:0)
试试吧。
SELECT a.ID, COUNT(a.ID) counta, (SELECT COUNT(b.ID) FROM b WHERE b.ID = a.ID GROUP BY b.ID) AS countb
FROM a
WHERE a.ID='7820193' GROUP BY a.ID
答案 3 :(得分:0)
这应该给你预期的结果,试一试:)
SELECT
z.id,
count(a.id) as count_ID_from_Table_A,
count(b.id) as count_ID_from_Table_B
FROM
(SELECT ID FROM table1
UNION
SELECT ID FROM table2) z
LEFT JOIN
table1 a ON z.id=a.id
LEFT JOIN
table2 b ON z.id=b.id
GROUP BY
z.id