Condtional insert using a 'WHERE' from another table - not the one inserted into
I want to be able to insert into one table but only if a condition is met on another table.
for example something like this
INSERT INTO table_1 (table_2_id,y,z) VALUES (123,2,3)
WHERE (
(SELECT COUNT(table_2_id) FROM table_2 WHERE valid=1 and id=123)=1
)
Basically - I want to only insert into table_1 if the related record 开发者_Python百科in table_2 is valid else it should fail.
is there a way to do this in one query or will I have to use some php+seperate query to do the check instead?
See whether this works for you:
INSERT INTO table_1 (table_2_id,y,z)
SELECT '123','2','3'
FROM table_2 WHERE valid=1 and id=123
精彩评论