一次执行两个选择时出现语法错误

时间:2014-08-06 12:03:21

标签: mysql sql

如何正确执行此sql查询,以免引发错误

  

SQL错误(1064):您的SQL语法中有错误;检查   手册,对应右边的MySQL服务器版本   在d.userId = us.userId set us.published =上使用')附近的语法   d.published,us.inactive = d.in'在第1行

当我在语句中添加第二个select时抛出错误。

update userStats us
join (select
  userId,
  sum(postStatus = 0) published,
  sum(postStatus = 1) inactive,
  sum(postStatus = 5) recalled,
  sum(postStatus = 6) deleted
from userData where userId = 1;

select 
    sum(postStatus = 10) unChecked
from userDataMod where userId = 1;// This causes the error.

) d on d.userId = us.userId set
us.published = d.published,
us.inactive = d.inactive,
us.recalled = d.recalled,
us.deleted = d.deleted
us.unChekced = d.unChecked
;

我已经看过一些运行这样的查询的例子,但是这个会引发错误。我不能在那里使用工会或其他任何东西。我该如何做到这一点?

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

   UPDATE userStats us
LEFT JOIN (
       SELECT userId,
              SUM(postStatus = 0) published,
              SUM(postStatus = 1) inactive,
              SUM(postStatus = 5) recalled,
              SUM(postStatus = 6) deleted
         FROM userData
     GROUP BY userId
          ) ud
       ON us.userId = ud.userId 
LEFT JOIN (
       SELECT userId,
              SUM(postStatus = 10) unchecked
         FROM userDataMod 
     GROUP BY userId
          ) udm
       ON us.userId = udm.userId
      SET us.published = COALESCE(ud.published,0),
          us.inactive = COALESCE(ud.inactive,0),
          us.recalled = COALESCE(ud.recalled,0),
          us.deleted = COALESCE(ud.deleted,0),
          us.unchecked = COALESCE(udm.unchecked,0)
    WHERE us.userID = 1

答案 1 :(得分:0)

我认为这是您想要的查询:

update userStats us join
       (select userId, sum(postStatus = 0) as published,
               sum(postStatus = 1) as inactive,
               sum(postStatus = 5) as recalled,
               sum(postStatus = 6) as deleted,
               (select sum(postStatus = 10) from userDataMod where userId = 1) as Unchecked
        from userData
        where userId = 1
       ) d
       on us.userid = d.userid
    set us.published = d.published,
        us.inactive = d.inactive,
        us.recalled = d.recalled,
        us.deleted = d.deleted
        us.unChekced = d.unChecked;

主要问题是您不能在查询中间使用分号。我认为你的子查询的位置也是关闭的。