【问题标题】:Odd behavior combining multiple tables and using COALESCE组合多个表并使用 COALESCE 的奇怪行为
【发布时间】:2017-02-28 01:52:15
【问题描述】:

我有一个很大的问题,我一直在苦苦调整和调整。

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;

如果结果还没有分数,我正在使用COALESCE(sum(tasteNoteRate.score),0) 为结果返回零值。

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

当我给一个分数时,他们都出现了,一个是分数,第二个是零。

【问题讨论】:

  • 您的查询基本上无效,因为您在使用GROUP BY 时选择了非聚合列。只有noteIDSUM() 属于您的SELECT 语句。
  • 用户能否在同一张纸条中多次评价同一种啤酒?
  • 所以这个查询带回了音符的分数。一个用户只能对给定笔记评分一次,但其他用户也可以对该笔记评分。

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


【解决方案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

【讨论】:

  • “WHERE”子句在哪里?
  • 返回错误:错误代码:1146。表 'BeerData.users' 不存在 0.109 秒
  • 是的,它是 user 表而不是用户。更新并提供了一个 SQLFiddle
  • 太棒了,这样行得通。但老实说,我不完全理解为什么并想学习。
猜你喜欢
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
相关资源
最近更新 更多