2011-05-16 255 views
2

我有一個名爲entry的mySQL表。它裏面有2個測試記錄:mySQL查詢幫助

SELECT * FROM entry WHERE typeId = 2 

SELECT * FROM entry WHERE typeId = 2

我有不同的類型。例如,當typeId = 2這是一個問題。當typeId = 3時,這是一個答案。當一個答案被插入到這個表格中時,linkId列會填入它正在回答的問題的entryId。

例如:

SELECT * FROM entry WHERE typeId = 3 

SELECT * FROM entry WHERE typeId = 3

正如你可以看到這兩個記錄是TYPEID = 3和鏈路ID都指向ENTRYID = 1

在下面的查詢我只會得到與其相關的答案。

SELECT SQL_CALC_FOUND_ROWS 
entry.entryId, entry.entryText, entry.voteCount AS voteCount, 
USER.userName, USER.fbId, COUNT(e2.entryId) AS answerCount 
FROM entry 
INNER JOIN USER ON entry.userId = USER.userId 
INNER JOIN entry AS e2 ON e2.linkId = entry.entryId AND e2.active=1 
WHERE entry.active = 1 
AND entry.typeId = 2 
ORDER BY entry.voteCount DESC 

above sql statement results

根據上面的語句我有2項是TYPEID的= 2,所以我真的很喜歡這個語句返回兩個條目,但顯然answerCount與任何答案入境將是0.

有沒有人有任何想法,我已經告訴你解決這個查詢來獲得所需的結果?

UPDATE:

基於關下方的建議。我改變了內連接至左連接:

SELECT SQL_CALC_FOUND_ROWS DISTINCT 
entry.entryId, entry.entryText, entry.voteCount AS voteCount, 
USER.userName, USER.fbId 
FROM entry 
INNER JOIN USER ON entry.userId = USER.userId 
LEFT JOIN entry AS e2 ON e2.linkId = entry.entryId AND e2.active=1 
WHERE entry.active = 1 
AND entry.typeId = 2 
ORDER BY entry.voteCount DESC 

在此聲明我拿出count語句(COUNT(e2.entryId)AS answerCount)。

這是結果:

SQL Left Join no COUNT

當我把在COUNT聲明它只返回返回時,它是內部1個記錄加入:

with COUNT and INNER JOIN

任何想法?

UPDATE:

我能得到的行通過確保LEFT JOIN是正確的,當我加了GROUP BY,然後用0回答行正常返回正常返回。

enter image description here

見下面我的查詢。感謝所有幫助!

回答

0

其實我得到它的工作...

這裏我的最新聲明:

SELECT e1.entryId, e1.entryText, e1.voteCount AS voteCount, 
USER.userName, USER.fbId, COUNT(e2.linkId) 
FROM entry e1 
INNER JOIN USER ON e1.userId = USER.userId 
LEFT JOIN entry e2 
ON e2.linkId = e1.entryId 
WHERE e1.active = 1 
AND e1.typeId = 2 
GROUP BY e1.entryId 
ORDER BY e1.voteCount DESC 

我按照建議添加了LEFT JOIN,但我也確保連接是正確的,拼圖的最後一部分是GROUP BY。一旦我把它放進去,我得到了我最初尋找的2排。

enter image description here

感謝所有幫助!

4

我想你第二個加入入境表應該是左連接:

INNER JOIN entry AS e2 ON e2.linkId = entry.entryId AND e2.active=1 

應該是:

LEFT JOIN entry AS e2 ON e2.linkId = entry.entryId AND e2.active=1 
+0

我同意@Tudor,嘗試使用LEFT JOIN,這應該清除你的問題。 – Jako 2011-05-16 04:24:31

+0

和@Jako - 我試過了,仍然得到了相同的結果。查看更新的信息。 – webdad3 2011-05-16 05:16:00

+0

如果您嘗試通過entry.entryId而不是e2.entryId進行計數,該怎麼辦? – 2011-05-16 05:38:31