简体   繁体   English

用子查询更新,左联接

[英]UPDATE With Subquery, Left Join

i am building an UPDATE query that is subject to a WHERE clause contained in a subquery. 我正在建立一个受子查询中包含的WHERE子句约束的UPDATE查询。

this query works when I restrict it to something like this : 当我将查询限制为以下内容时,此查询有效:

WHERE id=
( 
   SELECT 
      u.id
    FROM USER u
    WHERE
   u.live = 1 
)

however my query requires a further subquery within the subsquery. 但是我的查询需要在子查询中进一步的子查询。 below is an example of my query ; 下面是我查询的一个例子;

UPDATE newsletters     
 SET personalHtml =2
   WHERE id=
    (
      SELECT  
         u.id,
         (SELECT 
            COUNT(lo.userId)
          FROM    
            list_members_login lo
                WHERE 
                    u.id = lo.userId
                ) as totalLogins

                FROM
                    user u  
                WHERE
                    u.live = 1 
                 AND   
                    u.jobId IN (2,4) 
                GROUP BY 
                     u.id    
                    HAVING 
                        totalLogins >= 4 
               ) 

i am getting the following error message: 我收到以下错误消息:

Operand should contain 1 column(s) 操作数应包含1列

  1. The error means, it's expecting 1 value but subquery returning multiple results (say 1=(1,2,4) which is wrong). 该错误意味着,它期望值为1,但子查询返回多个结果(例如1 =(1,2,4),这是错误的)。 To resolve it you can use IN operand instead of = in where clause (say 1 IN (1,2,4)). 要解决它,您可以使用IN操作数代替where子句中的=(例如1 IN(1,2,4))。
  2. The subquery select should not contain multiple columns u.id and totalLogins in select clause. 子查询选择不应该包含多个列u.idtotalLogins在SELECT子句。

Try below code. 尝试下面的代码。 Hope this works. 希望这行得通。

UPDATE newsletters     
SET personalHtml =2
WHERE id IN
(
  SELECT  
         u.id
  FROM
          user u  
  WHERE
          u.live = 1 
  AND   
          u.jobId IN (2,4) 
  GROUP BY 
           u.id    
  HAVING 

            (SELECT 
                  COUNT(lo.userId)
                  FROM    
                  list_members_login lo
                  WHERE 
                  u.id = lo.userId
            ) >= 4 
   )

In your subquery you have 2 columns hence the error, remove totalLogins from subquery. 在您的子查询中,您有2列,因此出现错误,请从子查询中删除totalLogins。

Also be noted that if your subquery returns more than 1 value it will again give you error stating subquery returna more than 1 value.Consider using in instead of = 还需要注意的是,如果您的子查询返回的值大于1,它将再次给您错误,指出子查询返回的值大于1.考虑使用in代替=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM