MYSQL:计算另一个表中与第一个表中的行对应的行数

时间:2014-07-08 16:54:23

标签: php mysql sql join

我有三个表:帐户(企业列表,每个都有一个AccountID),联系人(人员列表,通过AccountID绑定到Accounts表)和ContactComments(各个联系人留下的评论列表,通过ContactID绑定到Contacts表)。我正在尝试显示所有联系人的列表,以及每个联系人收到的评论数量(有些评论为零)。这是我目前的查询:

    select
    a.ContactID, a.ContactType, a.FirstName, a.LastName, a.Phone, a.Email,
    b.AccountName, 
    c.ContactID, count(c.CommentID) as CountCon
    from
    Contacts a, Accounts b, ContactComments c 
    where 
    a.AccountID = b.AccountID 
    group by a.ContactID 
    order by a.LastName

当我通过PHP在我的页面上显示它时,我得到了这个:

Nonexistant Holdings, LLC   Larry Boe   941-555-8888    larry@example.com   View Comments   16

Another Subcontractor, Inc. Eric Coe    941-555-6000    eric@example.com    View Comments   16

Nonexistant Holdings, LLC   Yasmeen Crith   941-555-9999    yasmeen@asdf.com    View Comments   16

ABC Realty, Inc.    Jane Doe    941-555-1111    jane@example.com    View Comments   16

XYZ Properties, LLC Jim Foe 941-555-2222    jim@example.com View Comments   16

16,在每一行的末尾,是当前评论表中的评论总数。我意识到我的查询已关闭,因为我的计数(c.CommentID)当然是计算所有注释。如何调整此值以便我获得每个联系人的评论数并在每行的末尾显示(如果联系人没有评论,则包括零)?这是我需要加入才能完成的事情吗? (不太熟悉连接,但是。)

1 个答案:

答案 0 :(得分:0)

明确声明您的联接将帮助您查看您遇到问题的位置。例如,如果您明确声明了联接

,这大致是您的查询将转换为的内容
select
a.ContactID, a.ContactType, a.FirstName, a.LastName, a.Phone, a.Email,
b.AccountName, 
c.ContactID, count(c.CommentID) as CountCon
from
Contacts a
join Accounts b on a.AccountID = b.AccountID
join ContactComments c --(but you are missing join qualifiers so this would need to be declared as a cross join for your query to run)
group by a.ContactID 
order by a.LastName

你想要的是这个(编辑:根据评论员更新为ifnull):

select
a.ContactID, a.ContactType, a.FirstName, a.LastName, a.Phone, a.Email,
b.AccountName, 
c.ContactID, ifnull(count(c.CommentID), 0) as CountCon
from
Contacts a
join Accounts b on a.AccountID = b.AccountID
left join ContactComments c on a.ContactID = c.ContactID
group by a.ContactID 
order by a.LastName