SQL QUERY (DELETE BETWEEN TWO TABLES)
I need a query for PHP or an idea for this.
I have t开发者_JAVA百科wo tables:
News
ID MAME
--------
1 Test
2 Test1
3 Test2
4 Test3
7 Test3
Products
ID NAME PRICE
-------------
1 Test 11
9 Test2 22
8 Test4 122
I need to delete records from Products where ID doesn't exist in News.
Can someone help me with some ideas?
Thanks for your time!
Try SELECT * FROM PRODUCTS WHERE ID NOT IN (SELECT ID FROM NEWS)
If this works then change SELECT *
to DELETE
It's good practice to try a select to make sure you are getting the right data before you delete.
DELETE Products
FROM Products
LEFT JOIN News
USING (ID)
WHERE News.ID IS NULL;
If you want to check what gets deleted from products, use Paul's excellent suggestion of using a select first.
So check with
SELECT *
FROM Products
LEFT JOIN News
USING (ID)
WHERE News.ID IS NULL;
and switch back to
DELETE Products
FROM Products
LEFT JOIN News
USING (ID)
WHERE News.ID IS NULL;
if you are happy with the result. It's IMPORTANT you DELETE Products FROM
rather than DELETE FROM
, otherwise will will delete from both tables.
精彩评论