开发者

SQL QUERY (DELETE BETWEEN TWO TABLES)

开发者 https://www.devze.com 2023-03-17 07:11 出处:网络
I need a query for PHP or an idea for this. I have t开发者_JAVA百科wo tables: News ID MAME -------- 1 Test

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号