简体   繁体   English

连接三个不同的表

[英]Joining three different tables

I am trying to get the count value of two tables and use the member id as key to count the rows of the other tables, I have this code so far but it is outputting a big value for comCount and empty value for chatCount. 我试图获取两个表的计数值,并使用成员id作为键来计数其他表的行,到目前为止,我已经有这段代码,但是它为comCount输出一个大值,为chatCount输出一个空值。 Here is my code 这是我的代码

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'`
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'

As a sidenote, the query is vulnerable with SQL Injection if the value( s ) came from the outside. 作为一个旁注,查询是脆弱的SQL Injection ,如果值(S)从外面走了进来。 Please take a look at the article below to learn how to prevent from it. 请查看下面的文章,以了解如何防止它。 By using PreparedStatements you can get rid of using single quotes around values. 通过使用PreparedStatements,您可以摆脱在值周围使用单引号的麻烦。

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'`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM