mysql使用group计算来自一个表的行,并使用第二个表来计算连接

问题描述 投票:1回答:2

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

我有2张桌子:

表1:eventinfo

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

表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

在我需要的页面上,我需要计算参加此课程/活动的条目,以查看有多少座位可用。 (这种方式我知道如果我需要“告诉人们他们不能进入”我需要分组,因为在编码的这一点上划分并不重要。

好的,这是我的问题。上面的查询效果很好,除了我的缺陷之外还没有关于课程/活动的条目。我需要以上显示第二个日期初学者是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** <-----

我尝试了一些加入表格,但没有运气。 (奇怪的结果和数据库说我需要SET SQL_BIG_SELECTS = 1)

任何帮助都会非常感激。

mysql database jointable
2个回答
0
投票

如果我理解正确,一种方法使用相关子查询:

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

1
投票

使用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

© www.soinside.com 2019 - 2024. All rights reserved.