根据单独的表插入`COUNT(*)`

时间:2014-06-13 10:22:10

标签: php mysql

在MySQL中,是否可以从一个表中选择列,同时还可以根据其他表创建COUNT(*)列?这样,可以返回所有表的结果摘要。这可能有点令人困惑,无法用文字解释,所以我做了一些样本表:

events_tbl
----------------------------
id      |   eventname
1       |   Anime Festival
2       |   Food Festival   
----------------------------

booths_tbl
-------------------------
id      |   boothname
1       |   Walmart
2       |   Pizza Hut
3       |   Nike
4       |   North Face
-------------------------

participants_tbl
-----------------------------
id      |   participantname
1       |   John
2       |   Mike
3       |   Rambo
4       |   Minnie
-----------------------------

event_booths_tbl
--------------------------------
event_id        |       booth_id
1               |       1
1               |       2
1               |       5
2               |       3
2               |       4
--------------------------------

event_participants_tbl
-------------------------------------
event_id        |       booth_id
1               |       1
1               |       2
1               |       3
1               |       4
-------------------------------------

有没有办法在MySQL中获得这样的结果:

summary_tbl
------------------------------------------------------------------------
id  |   eventname       |   booth_count     |       participant_count
1   |   Anime Festival  |   3               |       4
2   |   Food Festival   |   2               |       0
------------------------------------------------------------------------

3 个答案:

答案 0 :(得分:1)

加入每个表中的子查询:

SELECT e.id, e.event_name, 
       IFNULL(b.booth_count, 0) AS booth_count, 
       IFNULL(p.participant_count, 0) AS participant_count
FROM events_table AS e
LEFT JOIN (SELECT event_id, COUNT(*) AS booth_count
           FROM event_booths_table
           GROUP BY event_id) AS b ON e.id = b.event_id
LEFT JOIN (SELECT event_id, COUNT(*) AS participant_count
           FROM event_participants_table
           GROUP BY event_id) AS p ON e.id = p.event_id

答案 1 :(得分:1)

event_participants_tbl应包含participant_id而不是booth_id。 否则无关紧要。 您的MySQL查询将如下所示:

select
 et.id,
 et.eventname,
 count(distinct ebt.booth_id) as booth_count,
 count(distinct ept.participant_id) as participant_count
from
 event_booths_tbl ebt
 left join events_tbl et on et.id=ebt.event_id
 left join event_participants_tbl ept on ept.event_id=ebt.event_id
group by et.event_id;

答案 2 :(得分:0)

试试这个:

    select event.id,
    event.name,
    count(distinct eventBooth.booth_id),
    count(distinct eventParitcipant.booth_id) 
    from events_tbl event
        LEFT JOIN event_booths_tbl eventBooth on eventBooth.event_id=event.id
        LEFT JOIN event_participants_tbl eventParitcipant 
                      on eventParitcipant.event_id=event.id
        group by event.id