How to Delete record from different table with out using sub query using sql or mysql.

If i want to delete record from a single table i just need to run a simple delete command like below .

Query to delete single record :

DELETE FROM
    `first_table`   
         WHERE
              `my_value`='FooBar';  


Now suppose i want to delete record from two different table then every person first comes in there mind using join with delete command like below :

Query with join return error :

DELETE FROM
    `first_table`
          INNER JOIN `second_table` ON `second_table`.`id_column`=`first_table`.`id_column`
             WHERE
               `my_value`='FooBar'; 

But you know above query return an error something like below :

#1064 - 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 'INNER JOIN `second_table` ON `second_table`.`id_column`=`my_table`.`id_column` WHERE `my_va' ne 1


The Solution :

Sticking with the query above we can get it to work with a simple amendment. All we need to do is put the name of the table we’re deleting from between the words ‘DELETE’ and ‘FROM’ like below.

Query with join  :

DELETE `first_table` FROM
    `first_table`
        INNER JOIN `second_table` ON `second_table`.`id_column`=`first_table`.`id_column`
         WHERE
           `my_value`='FooBar'; 


If you like this post don't forgot to leave a comment 

Chears  :)

Post a Comment

Previous Post Next Post