0
是否可以執行這樣的插入查詢?MySQL如果某個行在另一個表上不存在,則有條件地插入到一個表中
INSERT INTO `table_1`
VALUES ('val1','val2','val3')
WHERE (
SELECT COUNT(*)
FROM `table_2`
WHERE col1='somevalue'
)=0;
是否可以執行這樣的插入查詢?MySQL如果某個行在另一個表上不存在,則有條件地插入到一個表中
INSERT INTO `table_1`
VALUES ('val1','val2','val3')
WHERE (
SELECT COUNT(*)
FROM `table_2`
WHERE col1='somevalue'
)=0;
可以使用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_2
與其他的值不存在時,限制插入到table_1
中。NOT EXISTS
比使用COUNT(*)
更有效率。INSERT
時,應始終列出列。