How to use COUNT() with JOIN 3 tables

时间:2017-05-16 09:19:57

标签: mysql

I have three tables: account_info, gang_info and gang_join_info.

`account_info`:

u_id    name            g_id
---------------------------------
1       Philip          1
2       John            2

`gang_info`:

g_id    g_name          g_color
---------------------------------
1       U2              37497
2       The Invicibles  1517

`gang_join_info`:

p_id       g_id       a_id       t_id
---------------------------------
1          1          4          1493894713 --gang founder
1          2          2          1493894714
1          2          3          1493894713
1          2          3          1493894715
2          1          2          1494158866
2          2          4          1494834912 --gang founder

Result I want is:

g_id  g_color  FROM_UNIXTIME(gj.t_id, '%d %m %Y')  g_members   a_id  name        g_name
---------------------------------
1     37497    04 05 2017                          1           4     Philip      U2
2     1517     15 05 2017                          1           4     John        The Invicibles

My query is

SELECT g.g_id
     , g.g_color
     , FROM_UNIXTIME(gj.t_id, '%d %m %Y')
     , gj.a_id
     , name
     , g_name 
  FROM gang_info g 
  JOIN gang_join_info gj 
    ON g.g_id = gj.g_id 
  JOIN account_info a 
    ON a.u_id = gj.p_id 
HAVING gj.a_id = 4

With this query I need gangs information from gang_info, gang's creation time from gang_join_info with field a_id = 4, gang founder name from account_info. That I have already done with query up, but I also need amount of gang members. I tried this query

SELECT g.g_id, g_color, COUNT(a.g_id) AS g_members, FROM_UNIXTIME(t_id, '%d %m %Y'), a.name, g_name FROM gang_info g JOIN account_info a ON g.g_id = a.g_id JOIN gang_join_info gj ON g.g_id = gj.g_id AND gj.a_id = 4

But it don't work, amount of gang members returns good, but gang's data are wrong. Is this possible with one query?

EDIT:

Finally I got it, I needed a subquery. Here is working query:

SELECT g.g_id, g.g_color, (SELECT COUNT(*) FROM account_info a WHERE a.g_id = g.g_id) AS g_members, gj.a_id, FROM_UNIXTIME(gj.t_id, '%d %m %Y'), a.name, g.g_name
FROM gang_join_info gj
JOIN gang_info g ON gj.g_id = g.g_id
JOIN account_info a ON gj.p_id = a.u_id
HAVING gj.a_id = 4 AND g_members != 0

1 个答案:

答案 0 :(得分:0)

您需要添加group by子句:

SELECT g.g_id, g_color, COUNT(a.g_id) AS g_members, FROM_UNIXTIME(t_id, '%d %m %Y'), a.name, g_name
FROM gang_info g
JOIN account_info a ON g.g_id = a.g_id
JOIN gang_join_info gj ON g.g_id = gj.g_id AND gj.a_id = 4
GROUP BY 1,2,4,5,6 -- list all non-aggregated column numbers

MySQL(单独)不允许group by,但在这种情况下的行为不是你想要的。