在这个问题之后,我一直试图模仿在我的表中插入数据的正确答案。只有它是空的。
Execute INSERT if table is empty?
这是我的代码:
INSERT INTO `statuses` SELECT
('Something', 'Something else', 123),
('Something', 'Something else', 234)
WHERE NOT EXISTS (SELECT * FROM `statuses`);
但是如果表是空的,不是添加元素,而是我得到:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT * FROM `statuses`)'
我应该如何编写查询以便仅在表为空时才插入值?
答案 0 :(得分:3)
语句中有语法错误:
INSERT INTO `statuses`
(SELECT 'Something', 'Something else', 123
WHERE NOT EXISTS (SELECT * FROM `statuses`)
) union all
(SELECT 'Something', 'Something else', 234
WHERE NOT EXISTS (SELECT * FROM `statuses`)
);
在这种情况下,您需要重复where
两次,每个子查询一次。你也可以这样做:
INSERT INTO `statuses`
select t.*
from ((SELECT 'Something' as col1, 'Something else' as col2, 123 as col3
) union all
(SELECT 'Something', 'Something else', 234
)
) t
WHERE NOT EXISTS (SELECT * FROM `statuses`);
在此版本中,您需要为列指定名称。
或者,您可以使用两个单独的插入语句。
答案 1 :(得分:1)
正确的语法是:
INSERT INTO user_authentication
SELECT t.*
FROM ((SELECT 1 as col1, 'kingston' as col2, 'test' as col3, true as col4)) t
WHERE NOT EXISTS (SELECT * FROM user_authentication);
这对我有用。