mysql - 为什么 left outer join 对我来说失败了?

标签 mysql sql join

我看不出有什么问题,但为什么会这样

/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'left outer join votes on items.id = votes.parent and votes.userid = 1 group by i' at line 2 */


select maxVotes, sum(case when coalesce(votes.id, 0) then 1 else 0 end) votesCast from items where type = 'marker'
left outer join votes on items.id = votes.parent and votes.userid = 1 group by items.id;

我正在使用 mySql 执行此操作。

最佳答案

更改为

select maxVotes, 
       sum(case when coalesce(votes.id, 0) then 1 else 0 end) votesCast 
  from items left outer join votes -- <-- your JOIN clause should go here
    on items.id = votes.parent 
   and votes.userid = 1 
 where type = 'marker' -- <-- and WHERE here
group by items.id;

旁注:即使 MySql 允许在 SELECT 中指定一个不属于 GROUP BY 的字段(在您的情况下为 maxVotes),但它不是好事要做。您需要对该字段应用聚合函数(MAX、MIN...)。当您执行 GROUP BY items.id 时,无法判断要获取 maxVotes 的哪个值。

关于mysql - 为什么 left outer join 对我来说失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16706499/

相关文章:

mysql - SQL - 无法添加或更新子行 : a foreign key constraint fails - Pivot table

mysql - 在 SQL 查询中运行检查(也许是子查询?)

MySQL在匹配特定值时加入条件

javascript - 加入从 startIndex 到 endIndex 的数组

mysql - 添加具有默认值的非空列时,是否在 MySQL 中记录行级 binlog 条目

php - 在 BD 中搜索存储有 á 元素的值

c# - LIKE 的 SQL 语法帮助

sql - 如何递增 id 字段的所有存储值

PHP、MySQL 和 Join with SUMs

mysql - 与 null 相比,为什么零日期不是 null?