0

我有两张桌子,想计算两张桌子上的身份证号码。一张表只会有一个结果,但另一张可能会有更多。

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 count(b.ID)=200

但是,在我尝试过的所有类型的连接(左、右、内)中,只有一个该 ID 号的实例我做错了什么?

4

4 回答 4

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
于 2013-04-03T09:43:22.960 回答
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;
于 2013-04-03T09:45:44.830 回答
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
于 2013-04-03T09:50:47.617 回答
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
于 2016-06-14T07:26:59.817 回答