mysql连接2个表并计算每个表中的所有行

时间:2012-07-02 14:25:07

标签: mysql join count

我有表合约c(id,exp_date)和表成员m(id,cid)。 我需要计算所有合同和所有成员一起加入m.cid = c.id上的2个表。

我试过这个,但显然不是正确的,因为它从两个表中返回相同的计数结果

SELECT count(m.id) as totmembers , count(c.id) as totcontracts
from members m
join contracts c on m.cid = c.id
where DATEDIFF(c.im_exp, CURDATE()) > 0

结果应该是5000个合同,12.000个成员,但我会得到12.000的东西和totcontracts。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT count(m.id) as totmembers , count(distinct c.id) as totcontracts
from members m
join contracts c on m.cid = c.id
where DATEDIFF(c.im_exp, CURDATE()) > 0

答案 1 :(得分:0)

因为您创建了一个INNER JOIN语句。在SELECT列表中创建一个包含两个单独查询的新查询。

SELECT (SELECT ... WHERE ...) AS totmembers, (SELECT ... WHERE ...) AS totcontracts