所选行的SQL更新

时间:2017-01-16 15:35:29

标签: mysql select sql-update

我有这个SQL代码:

SELECT * FROM `clients_branches` 
         WHERE NULLIF(clients_branches.invoice_email, '') IS NULL 
         GROUP BY client_code 
         HAVING COUNT(*) = 1 

它返回在数据库中只出现一次的所有行,也只返回没有设置电子邮件的行。现在我需要将UPDATE函数应用于所有这个select语句。我怎么能这样做?我需要为所有这些行设置clients_branches.invoice_send为0。

我似乎无法在UPDATE语句中使用HAVING COUNT,如下所示:

UPDATE `clients_branches` 
SET clients_branches.invoice_send = 0 
WHERE NULLIF(clients_branches.invoice_email, '') IS NULL
HAVING COUNT(*) = 1 

如果没有HUNTING COUNT,我将更改在此表中至少重复一次的所有行。我只需要更改count = 1的那些。

1 个答案:

答案 0 :(得分:1)

您可以使用联接来允许使用表进行更新以及查询结果

  update `clients_branches` 
  JOIN 
  (  
    select client_code, count(*)
    FROM `clients_branches` 
    WHERE NULLIF(clients_branches.invoice_email, '') IS NULL 
    group by client_code 
    HAVING COUNT(*) = 1 
  ) t on t.client_code = `clients_branches`.client_code
  set clients_branches.invoice_send =  0
  ;