2017-06-24 38 views
0

表中有一個foundStatus列,它是一個char。我想回到foundStatuses列表與旁邊的每個計數 - 這個工程:按內部連接返回太多記錄

SELECT foundstatus, count(foundstatus) as total 
FROM findings f 
WHERE findDateTime BETWEEN '2008-01-01' AND '2017-06-24 23:59:59' 
group by foundstatus 
order by foundstatus 

我需要加入一些表來建立一個where子句 - 而這樣做開始返回太多的列。我能得到這個工作:

SELECT foundstatus, count(foundstatus) as total 
FROM findings f left join 
    pets p 
    on f.petid = p.petid 
WHERE findDateTime BETWEEN '2008-01-01' AND '2017-06-24 23:59:59' 
group by foundstatus 
order by foundstatus 

通過這樣做左連接,但是 - 任何後續加入我(左或內部)剛剛返回過多行(我猜是因爲返回連接表的多個記錄) :

SELECT foundstatus, count(foundstatus) as total 
FROM findings f left join 
    pets p 
    on f.petid = p.petid inner join 
    petTags pt 
    ON p.petID = pt.petID 
WHERE findDateTime BETWEEN '2008-01-01' AND '2017-06-24 23:59:59' 
group by foundstatus 
order by foundstatus 

我需要一個像只有5個連接表底部的語句才能返回與前2個查詢相同的計數。我相信這很容易,但在Google上什麼也找不到 - 我該怎麼辦?謝謝。

+0

人們在堆棧溢出中如何堆積如此多的點,而不知道如何格式化代碼? –

+1

@GordonLinoff我真的很喜歡他的方式比你更多 - 我喜歡新行上的連接和與同一行上的連接相關的表名。所以一行有FROM <文件來自>或JOIN <表加入> – Hogan

+1

我在這裏閱讀的最好的問題之一,總是很高興地讀你的答案教授。 @Gordon – Frank

回答

2

假設你有findings主鍵,你可以這樣做:

select f.foundstatus, count(distinct f.findingsId) as total 
from findings f left join 
    pets p 
    on f.petid = p.petid left join 
    petTags pt 
    on p.petID = pt.petID 
where f.findDateTime >= '2008-01-01' and 
     f.findDateTime < '2017-06-25' 
group by f.foundstatus 
order by foundstatus; 

通常,count(distinct)是不是最好的一段路要走。我的猜測是WHERE條款中的EXISTS條件是更好的方式來做你想做的事情。

+0

謝謝 - 這實際上返回的計數*太低*這次。例如有效的foundStatus ='I'。這在結果表中出現了5次 - 但上面的SQL只返回3個。(5箇中有3個具有相同的相關petID - 我認爲這是原因,這3箇中只有1個被計數,+2個爲更多共3個)。 – niico

+0

'count(distinct petId)'? – Hogan

+0

好的,我解決了它 - 它只需要2個左連接。謝謝! – niico