SELECT IF((SELECT id FROM users where store='XXX' limit 1) IS NULL, null, (SELECT id FROM users where store='XXX' limit 1)) INTO @user_id;
select @user_id;
INSERT INTO `orders`(`user_id`)VALUES(@user_id);
我需要的是当@user_id为NULL时我不想插入到我的表命令中。如果我在insert语句上面放了一个if else语句,我会收到一条错误,说“语法错误意外IF”。
答案 0 :(得分:0)
使用IFNULL功能,这样:
SELECT IFNULL(condition, value_if_condition_is_null)
在您的查询中,例如:
SELECT IFNULL((SELECT id FROM users where store='XXX' limit 1), (SELECT id FROM users where store='XXX' limit 1))) INTO @user_id;