我需要使用IF
语句创建MySQL查询。这是一个数据库模式:
CREATE DATABASE my_db;
USE my_db;
CREATE TABLE IF NOT EXISTS if_table(
id INTEGER unsigned,
field_1 INTEGER unsigned,
field_2 INTEGER unsigned,
field_3 INTEGER unsigned,
PRIMARY KEY (id)
);
如何编写与下一个伪代码对应的UPDATE
查询?
if field_2 equals 0 then field_1 = field_1 + 1
else field_3 = field_3 + 2
where id == 1
答案 0 :(得分:4)
尝试此内联 IF
声明
SELECT IF(field_2 = 0, field_1 + 1, field_3 + 2) AS `Result`
FROM tableName
WHERE ID = 1
击> <击> 撞击> 或者如果你想更新价值,
UPDATE tableName
SET field_1 = IF(field_2 = 0, field_1 + 1, field_1),
field_3 = IF(field_2 = 0, field_3, field_3 + 2)
WHERE ID = 1
答案 1 :(得分:1)
你可以用两个查询来完成。
UPDATE table_name SET field_1 = field_1 + 1 WHERE id = 1 AND field_2 = 0;
UPDATE table_name SET field_3 = field_3 + 2 WHERE id = 1 AND field_2 != 0;
如果您只想要一个查询,那么
UPDATE table_name
SET field_1 = IF(field_2 = 0, field_1 + 1, field_1),
SET field_3 = IF(field_2 = 0, field_3, field_3 + 2),
WHERE ID = 1