简体   繁体   中英

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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