mySQL查询帮助

时间:2011-05-16 04:05:57

标签: mysql sql tsql

我有一个名为entry的mySQL表。它有2个测试记录:

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而linkId都指向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。

有没有人对我向您展示的内容有什么想法来修复此查询以获得所需的结果?

更新

基于以下建议。我将内连接更改为左连接:

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

有什么想法吗?

更新

通过确保LEFT JOIN是正确的,当我添加GROUP BY时,我能够正确地返回行,然后正确返回0回答的行。

enter image description here

请参阅下面的查询。谢谢大家的帮助!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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。一旦我把它放进去,我得到了我原本想要的两行。

enter image description here

感谢您的帮助!