user1177437
user1177437

Reputation: 79

mysql query calculation with join different tables

I'm using MySQL 4.2, and I'm have 2 tables:

tbl_User stores USERID and REGCODE. REGCODE is the code user used for signup the service. tbl_Message stores messages posted by each of those users.

I need to query all users in tbl_User for the corresponding REGCODE to get total. Then, I would like to know is how many of these users have at least one entry in tbl_Message where their USERID matches up with AUTHORID. The last row is the % of user has post.

My goal is to calculate the percentage from two tables at last row, but I am not sure how to join tables in query to get the correct answer.

Tables chart: http://img526.imageshack.us/img526/6105/tablep.png

I asked this question yesterday, and @mathematical.coffee told me a simple query to get the result I want. It worked at first, but I found the query some issue with COUNT(tbl_User.USERID) and left join after I accepted the answer.

As you can see from this query, "COUNT(tbl_User.USERID) as totalUsers" is affected by the left join condition, thus the number of total users is wrong. Can someone help me this, thanks so much!

SELECT REGCODE,
       COUNT(tbl_User.USERID) as totalUsers, 
       COUNT(tbl_Message.MESSAGEID) as usersWhoPosted 
       COUNT(tbl_Message.MESSAGEID)/COUNT(tbl_User.USERID)*100 As Percent
FROM tbl_User 
LEFT JOIN tbl_Message ON tbl_User.USERID=tbl_Message.AUTHORID 
WHERE REGCODE BETWEEN 9001 AND 9008
GROUP BY REGCODE

Result:

REGCODE   totalUsers  usersWhoPosted  Percent
9001      763         233             30.5374
...   
9008      345         235             68.1159

Upvotes: 1

Views: 707

Answers (1)

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115650

You can modify your query to use DISTINCT. The usersWhoPosted count needs modification, too. Your query is counting messages posted, not users who posted:

SELECT 
    REGCODE,
    COUNT(DISTINCT tbl_User.USERID) AS totalUsers, 
    COUNT(DISTINCT tbl_Message.AUTHORID) AS usersWhoPosted 
    COUNT(DISTINCT tbl_Message.AUTHORID)/COUNT(DISTINCT tbl_User.USERID) * 100 
      AS Percent
FROM tbl_User 
   LEFT JOIN tbl_Message 
     ON tbl_User.USERID = tbl_Message.AUTHORID 
WHERE REGCODE BETWEEN 9001 AND 9008
GROUP BY REGCODE

You can also rewrite it like this:

SELECT 
    REGCODE,
    COUNT(*) AS totalUsers, 
    COUNT(HasPosted) AS usersWhoPosted 
    COUNT(HasPosted)/COUNT(*) * 100 
      AS Percent
FROM tbl_User 
   LEFT JOIN (SELECT 1 AS HasPosted) AS dummy 
     ON EXISTS
        ( SELECT *
          FROM tbl_Message
          WHERE tbl_User.USERID = tbl_Message.AUTHORID
        ) 
WHERE REGCODE BETWEEN 9001 AND 9008
GROUP BY REGCODE

Upvotes: 1

Related Questions