簡體   English   中英

mysql使用組從一個表中計算行並從第二個表中加入

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

我需要一些指導。 我在我的編碼中發現了一個缺陷。

我有2張桌子:

表 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

表 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)

任何幫助將不勝感激。

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

演示

如果我理解正確,一種方法使用相關子查詢:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM