MySQL根据另一个字段中的值更新字段

时间:2018-10-11 22:51:03

标签: mysql sql

我需要根据另一个字段中字符串的存在来更新一个字段。我需要对数百个搜索字符串执行此操作。到目前为止,这是我所拥有的:

SET SQL_SAFE_UPDATES=0;

UPDATE business_table
SET `chain` = '7-Eleven'
WHERE business_name LIKE BINARY '%7-Eleven%' OR business_name LIKE 
BINARY '%7 Eleven%';

UPDATE business_table
SET `chain` = 'A&W'
WHERE business_name LIKE '%A & W%' OR business_name LIKE '%A&W%';

UPDATE business_table
SET `chain` = 'Blenz Coffee'
WHERE business_name LIKE BINARY '%Blenz Coffee%';

UPDATE business_table
SET `chain` = 'Booster Juice'
WHERE business_name LIKE BINARY '%Booster Juice%';

UPDATE business_table
SET `chain` = 'Boston Pizza'
WHERE business_name LIKE BINARY '%Boston Pizza%';

SET SQL_SAFE_UPDATES=1;

有没有更有效的方法?我尝试将其放入存储过程中而不禁用SQL_SAFE-UPDATES,如下所示:

UPDATE business_table b
SET `chain` = '7-Eleven'
WHERE b.id = (SELECT id FROM b WHERE business_name LIKE BINARY '%7-Eleven%' OR business_name LIKE BINARY '%7 Eleven%');

我收到此错误:

Error Code: 1093. You can't specify target table 'b' for update in FROM clause

所以我了解这个错误是什么,但是我不知道如何解决这个错误;有数百条UPDATE语句。

想法?

1 个答案:

答案 0 :(得分:0)

是的,但这仅是因为您的update需要全表扫描。在模式开头将like与通配符一起使用会阻止任何有用的索引。

因此,您可以这样做:

UPDATE business_table
    SET chain = (CASE WHEN business_name LIKE BINARY '%7-Eleven%' OR business_name LIKE 
BINARY '%7 Eleven%' THEN '7-Eleven'
                      WHEN (business_name LIKE '%A & W%' OR business_name LIKE '%A&W%') THEN 'A&W'
                      . . .
                 END)
    WHERE (business_name LIKE BINARY '%7-Eleven%' OR business_name LIKE 
BINARY '%7 Eleven%') OR
          (business_name LIKE '%A & W%' OR business_name LIKE '%A&W%') OR
          . . .

您需要填写WHERE中的其余条件和CASE中的条件。