3

我在这里没有看到任何问题,但是为什么这给了我

/* 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 执行此操作。

4

3 回答 3

2

移动你的JOINbeforeWHERE子句:

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;
于 2013-05-23T05:56:53.360 回答
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 允许指定一个字段(在您的情况下为 maxVotes),SELECT这不是GROUP BY它的一部分,但这不是一件好事。您需要将聚合函数应用于该字段 ( MAX, MIN...)。maxVotes当你这样做时,没有办法知道要获取哪个值GROUP BY items.id

于 2013-05-23T05:57:29.163 回答
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;
于 2013-05-23T05:58:33.163 回答