即使列存在,使用更新和连接时的未知列也是如此

时间:2014-08-07 09:14:31

标签: mysql sql

我使用以下sql更新名为userStats的表格,并按照我提供的userId用户运行。

update userStats us
join (select
    sum(postStatus = 0) published,
    sum(postStatus = 1) inactive,
    sum(postStatus = 5) recalled,
    sum(postStatus = 6) deleted
from userData where userId = @x) d on d.userId = us.userId 
set
us.published = coalesce(d.published,0),
us.inactive = coalesce(d.inactive,0),
us.recalled = coalesce(d.recalled,0),
us.deleted = coalesce(d.deleted,0),
us.total = coalesce(d.published+d.inactive+d.recalled+d.deleted,0);

即使列中存在列,我也会遇到错误Unknown column 'd.userId' in 'on clause'。我过去经常使用这个相同的东西而没有错误。

此外,关于where的使用,在设置列之后需要另一个where,或者内部的位置是否足以仅更新userId I供应。它确实只更新userId我提供的内容,但是在那里之后再使用一个where我感到非常不舒服。我是否需要在外面像我之前做过的另一个?

us.deleted = coalesce(d.deleted,0),
us.total = coalesce(d.published+d.inactive+d.recalled+d.deleted,0) where userId =@x;

3 个答案:

答案 0 :(得分:1)

更改子查询

select
    sum(postStatus = 0) published,
    sum(postStatus = 1) inactive,
    sum(postStatus = 5) recalled,
    sum(postStatus = 6) deleted,userId 
from userData where userId = @x

然后在其工作的where子句中使用userid

答案 1 :(得分:1)

表格别名为d,虽然您的userID表格具有值,但未明确选择列userData

所以,你应该做的事情如下:

(select
    userID,  --> This field has to be selected to use in the join condition
    sum(postStatus = 0) published,
    sum(postStatus = 1) inactive,
    sum(postStatus = 5) recalled,
    sum(postStatus = 6) deleted
from userData where userId = @x) d on d.userId = us.userId 
                                         ^
                                         |___ You were getting error here.

答案 2 :(得分:1)

因为您只从内部查询中获取一行,所以您不需要连接条件!

update userStats us
join (select
    sum(postStatus = 0) published,
    sum(postStatus = 1) inactive,
    sum(postStatus = 5) recalled,
    sum(postStatus = 6) deleted
    from userData where userId = @x) d
set
us.published = coalesce(d.published,0),
us.inactive = coalesce(d.inactive,0),
us.recalled = coalesce(d.recalled,0),
us.deleted = coalesce(d.deleted,0),
us.total = coalesce(d.published+d.inactive+d.recalled+d.deleted,0)
where userid = @x

但是你的目标表中确实需要一个where子句。

此查询也可以很好地执行,因为内部和外部查询都使用索引友好的wher子句。