是否可以像这样执行插入查询?
INSERT INTO `table_1`
VALUES ('val1','val2','val3')
WHERE (
SELECT COUNT(*)
FROM `table_2`
WHERE col1='somevalue'
)=0;
答案 0 :(得分:2)
您可以使用insert . . . select
:
INSERT INTO `table_1`(col1, col2, col3)
SELECT col1, col2, col3
FROM (SELECT 'val1' as col1,'val2' as col2, 'val3' as col3) t
WHERE NOT EXISTS (SELECT 1
FROM table_2 t2
WHERE t2.col1 = 'somevalue'
);
注意:
table_1
中其他值不存在任何行时,将插入限制为table_2
。NOT EXISTS
比使用COUNT(*)
更有效。INSERT
时,您应始终列出列。