组合多个表并使用COALESCE的奇怪行为

时间:2017-02-28 01:52:15

标签: mysql join left-join inner-join coalesce

我有一个很大的疑问,我一直在努力和调整一段时间。

\1

如果他们还没有得分,我使用SELECT tastingNotes.userID, tastingNotes.beerID, tastingNotes.noteID, tastingNotes.note, user.userName, COALESCE(sum(tasteNoteRate.score),0) as `score` FROM tastingNotes INNER JOIN `user` on tastingNotes.userID = `user`.userID LEFT JOIN tasteNoteRate on tastingNotes.noteID = tasteNoteRate.noteID WHERE tastingNotes.beerID = 'C5RJc0' GROUP BY tastingNotes.noteID ORDER BY score DESC LIMIT 0,50; 给结果返回零值。

奇怪的是,当我应该有两个结果时,它只返回一个得分为零的音符。

当我给出一个得分时,他们都出现了,一个得分,然后第二个为零。

1 个答案:

答案 0 :(得分:1)

尝试

SELECT q.noteID, q.userID, q.beerID, q.note, q.score, u.userName
  FROM (
  SELECT n.noteID, n.userID, n.beerID, n.note, COALESCE(SUM(r.score), 0) score
    FROM tastingNotes n LEFT JOIN tasteNoteRate r
      ON n.noteID = r.noteID
   WHERE n.beerID = 'C5RJc0'
   GROUP BY n.noteID, n.userID, n.beerID, n.note
) q JOIN `user` u ON q.userID = u.userID
ORDER BY score DESC
LIMIT 50

SQLFiddle

相关问题