为什么左外连接在这里失败?

时间:2013-05-23 05:54:34

标签: 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做的。

3 个答案:

答案 0 :(得分:2)

JOIN子句之前移动WHERE

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

答案 1 :(得分:2)

更改为

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...)。执行maxVotes时无法确定GROUP BY items.id的哪个值。

答案 2 :(得分:1)

试试这个......

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