mysql 使用组从第一个 table 开始计算行数并从第二个 table 加入

mysql count rows from one table using group and join from 2nd table

我需要一些指导。我在我的编码中发现了一个缺陷。

我有 2 个 table:

table 1: 事件信息

id
evid
eventtype
division
evtdate
tod

加上更多字段,但对此并不重要

SQL查询:

SELECT evid, eventype, evtdate , tod 
FROM `eventinfo` 
WHERE evid =  105 


eventtype     division  evtdate tod
beginner        0   2018-02-17  AM
intermediate    1   2018-02-17  AM
intermediate    2   2018-02-17  AM
advanced        1   2018-02-17  AM
advanced        2   2018-02-17  AM
beginner        0   2018-02-18  AM
intermediate    1   2018-02-18  AM
intermediate    2   2018-02-18  AM
advanced        1   2018-02-18  AM
advanced        2   2018-02-18  AM

table 2: 条目

id
entid
firstname
lastname
eventcat
evtdate
division
tod

加上更多行,但对此并不重要。

SQL查询:

SELECT evid, eventcat, evtdate , tod , COUNT( * ) AS count 
FROM entries 
WHERE evtid= '105' and  evtstatus= 'pending' 
GROUP BY evtdate, tod , evntcat

eventcat        evtdate     tod count
Advanced        2018-02-17  AM  35
Intermediate    2018-02-17  AM  18
Beginner        2018-02-17  AM  4
Advanced        2018-02-18  AM  35
Intermediate    2018-02-18  AM  18

在我需要的页面上,我需要计算此 course/event 中的条目数以查看还有多少座位可用。 (这样我就知道我是否需要 "tell people they can't enter" 我需要分组,因为在编码的这一点上划分并不重要。

好的,这是我的问题。上面的查询效果很好,除了我的缺陷是 course/event 还没有条目。我需要上面的内容来表明第 2 个日期初学者是 0。(我知道我当前的查询不会显示)

eventcat        evtdate     tod count
Advanced        2018-02-17  AM  35
Intermediate    2018-02-17  AM  18
Beginner        2018-02-17  AM  4
Advanced        2018-02-18  AM  35
Intermediate    2018-02-18  AM  18
**Beginner        2018-02-18  AM  0** <-----

我尝试了一些加入 table 的方法,但没有成功。 (奇怪的结果和数据库说我需要 SET SQL_BIG_SELECTS=1)

如有任何帮助,我们将不胜感激。

如果我没理解错的话,一种方法是使用相关子查询:

select ei.*,
       (select count(*)
        from entries e
        where e.evtid = ei.evtid and e.evtstatus = 'pending'
       ) as cnt
from eventinfor ei

使用LEFT JOIN:

 SELECT i.eventtype, i.evtdate , i.tod , COUNT( * ) AS count 
FROM eventinfo AS i
LEFT JOIN entries as e On e.eventcat = i.eventtype
GROUP BY i.eventtype, i.evtdate , i.tod ;

demo