Insert into a table if row in another table exists
Posted: Sun Mar 29, 2009 2:41 pm
How would I write a MySQL statement that will insert a row into one table only if a row in another table exists. I tried something like this:
But I get an error:
I need to be able to do this because I only would like to insert flags into the table post_flags if there is a corresponding post in the posts table.
Code: Select all
IF EXIST(SELECT * FROM `posts` WHERE `post_id` = $id) THEN INSERT INTO `post_flags` (`post_id`, `ip_num`, `reason`) VALUES ($id, INET_ATON('$ip'), '$reason');
How can I insert a row into a table only if a row in another table exists?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 'IF EXIST(SELECT * FROM `posts` WHERE `post_id` = 6) THEN INSERT INTO `post_flags' at line 1
I need to be able to do this because I only would like to insert flags into the table post_flags if there is a corresponding post in the posts table.