我尝试同时执行这三个查询,但是我只能分别执行每个查询。
UPDATE post SET category=CONCAT(category,',2') WHERE id = 1 AND category LIKE '%5%' AND category LIKE '%1%';
UPDATE post SET category=CONCAT(category,',4') WHERE id = 1 AND category LIKE '%5%' AND category LIKE '%2%';
UPDATE post SET category=CONCAT(category,',6') WHERE id = 1 AND category LIKE '%5%' AND category LIKE '%3%';
我不明白如何正确编写查询:
UPDATE post SET
category = CONCAT(category,',2')IF(id 1 AND category LIKE '%1%'),
category = CONCAT(category,',4')IF(id 1 AND category LIKE '%2%'),
category = CONCAT(category,',6')IF(id 1 AND category LIKE '%3%')
WHERE id 1 AND category LIKE '%5%';
答案 0 :(得分:2)
您可以使用CASE语句完成当前任务
UPDATE post
SET category = CASE
WHEN category LIKE '%1%' THEN CONCAT(category,',1')
WHEN category LIKE '%2%' THEN CONCAT(category,',2')
WHEN category LIKE '%3%' THEN CONCAT(category,',3')
ELSE category
END
WHERE id = 1 AND category LIKE '%5%'
但是此任务意味着您数据库的结构是错误的,需要进行规范化。您应该阅读第一种规范化表格
答案 1 :(得分:0)
在IF函数中使用条件分支:
UPDATE post
SET category = IF(category LIKE '%1%',
CONCAT(category,',2'),
IF(category LIKE '%2%',
CONCAT(category,',4'),
IF(category LIKE '%3%',
CONCAT(category,',6'),
category
)
)
)
WHERE id = 1
AND category LIKE '%5%'