Reputation: 2764
Is it possible to do an insert query like this?
INSERT INTO `table_1`
VALUES ('val1','val2','val3')
WHERE (
SELECT COUNT(*)
FROM `table_2`
WHERE col1='somevalue'
)=0;
Upvotes: 0
Views: 1678
Reputation: 1269493
You can do this using 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'
);
Notes:
table_1
when no row exists in table_2
with other values.NOT EXISTS
is more efficient than using COUNT(*)
.INSERT
.Upvotes: 4