表连接与count()条件

时间:2012-03-20 23:58:55

标签: mysql sql

我需要找到至少有1个发行记录的所有顾客。这是我现在拥有的,但它只找到一个结果。我做错了什么?

SELECT * 
FROM patrons 
    INNER JOIN circulations on circulations.patron_id = patrons.id 
HAVING COUNT(circulations.id) > 0

我没有给表结构,因为我认为解决方案不需要它。如果需要,请告诉我,我会尝试将其添加到问题

4 个答案:

答案 0 :(得分:4)

怎么样:

SELECT * FROM patrons 
WHERE EXISTS (SELECT 1 FROM circulations 
              WHERE circulations.patron_id = patrons.id)

答案 1 :(得分:3)

以下内容应该有效:

SELECT * 
FROM patrons 
    INNER JOIN circulations on circulations.patron_id = patrons.id 
GROUP BY patrons.id

答案 2 :(得分:0)

查看我的样本:

假设PatronName是顾客桌上的一栏。

SELECT PatronName,COUNT(circulations.id) as CountCirculation
FROM patrons 
    INNER JOIN circulations on circulations.patron_id = patrons.id 
group by PatronName
HAVING COUNT(circulations.id) > 0

此致

答案 3 :(得分:0)

尝试......

select *
from patrons p
left join circulation c on c.patron_id = p.id
where not c.patron_id is null