加入三个不同的表

时间:2013-01-14 02:58:00

标签: php mysql sql select

我正在尝试获取两个表的计数值并使用成员id作为键来计算其他表的行数,到目前为止我有这个代码,但它为comCount输出一个大值,为chatCount输出空值。这是我的代码

SELECT members.*
, comments.commenter_id
, cb.user_id
, COUNT(comments.comment) AS comCount
, COUNT(cb.message) AS chatCount
FROM members 
INNER JOIN comments ON members.id = comments.commenter_id
INNER JOIN chat_box AS cb ON members.id = cb.user_id
WHERE members.id ='$profileId'`

2 个答案:

答案 0 :(得分:1)

SELECT  members.* , 
        a.commenter_id , 
        b.user_id , 
        a.totalComment , 
        b.totalChat
FROM    members 
        INNER JOIN 
        (
            SELECT commenter_id, COUNT(*) totalComment
            FROM comments
            GROUP BY commenter_id
        ) a ON members.id = a.commenter_id
        INNER JOIN 
        (
            SELECT user_id, COUNT(*) totalChat
            FROM chat_box 
            GROUP BY user_id            
        ) b  ON members.id = b.user_id
WHERE   members.id = '$profileId'

作为旁注,如果值( s )来自外部,则查询容易被SQL Injection攻击。请查看下面的文章,了解如何防止它。通过使用PreparedStatements,您可以摆脱在值周围使用单引号。

答案 1 :(得分:0)

SELECT members.*
, comments.commenter_id
, cb.user_id
,(select  COUNT(1) from comments where commenter_id = members.id) AS comCount
,(select count(1) from chat_box where user_id = members.id) AS chatCount
FROM members 
WHERE members.id ='$profileId'`