将多个sql更新语句合并为一个语句

时间:2019-06-25 21:11:20

标签: mysql

我有以下与MySQL一起使用的更新语句:

UPDATE billing_info_test SET Enagement = '800000032764' WHERE LinkedAccountId = '123456789101' AND Engagement = '800000026680';
UPDATE billing_info_test SET Enagement = '808000000000' WHERE LinkedAccountId = '123456789101' AND Engagement = '807000000041';
UPDATE billing_info_test SET Enagement = '807000000412' WHERE LinkedAccountId = '123456789101' AND Engagement = '870000012569';
UPDATE billing_info_test SET Enagement = '808000000223' WHERE LinkedAccountId = '123456789101' AND Engagement = '807000000279';
UPDATE billing_info_test SET Enagement = '808000000223' WHERE LinkedAccountId = '123456789101' AND Engagement = '807000000282';
UPDATE billing_info_test SET Enagement = '808000000223' WHERE LinkedAccountId = '123456789101' AND Engagement = '870000000403'; 

我如何将它们全部合并成一条语句?

3 个答案:

答案 0 :(得分:3)

您可以使用CASE表达式:

UPDATE billing_info_test 
SET Enagement = CASE Enagement
                     WHEN '800000026680' THEN '800000032764'
                     WHEN '807000000041' THEN '808000000000'
                     WHEN ... THEN ...
                END
WHERE LinkedAccountId = '123456789101' 
  AND Engagement IN ('800000026680', '807000000041', ...);

答案 1 :(得分:1)

您可以将所有六个UPDATE语句合并为一个语句,如下所示:

UPDATE billing_info_test 
SET Enagement = 
  case when Engagement = '800000026680' then '800000032764'
       when Engagement = '807000000041' then '808000000000'
       when Engagement = '870000012569' then '807000000412'
       when Engagement = '807000000279' then '808000000223'
       when Engagement = '807000000282' then '808000000223'
       when Engagement = '870000000403' then '808000000223'
  end
WHERE LinkedAccountId = '123456789101' 
  and Engagement in ('800000026680', 
                     '807000000041', 
                     '870000012569', 
                     '807000000279', 
                     '807000000282', 
                     '870000000403')

如果您的目标是高性能,那么也可以批处理所有六个UPDATE语句,这些语句可能更易于编写和调试。

答案 2 :(得分:1)

通过使用联接,可以避免在SET和WHERE子句中同时复制列值:

UPDATE billing_info_test b INNER JOIN (
  SELECT '800000026680' Engagement, '800000032764' NewEngagement UNION ALL
  SELECT '807000000041', '808000000000' UNION ALL
  SELECT '870000012569', '807000000412' UNION ALL
  SELECT '807000000279', '808000000223' UNION ALL
  SELECT '807000000282', '808000000223' UNION ALL
  SELECT '870000000403', '808000000223'  
) t ON b.Engagement = t.Engagement 
SET b.Engagement = t.NewEngagement 
WHERE b.LinkedAccountId = '123456789101';

请参见demo