0

I need a query for PHP or an idea for this.

I have two 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!

1

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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.

7 Comments

He wants to delete FROM Products, not News. Will this still work?
Yes, DELETE Products FROM [table_reference] means it will only delete the rows from the products table. Basically, all rows from products which are in the set of results from the join will be deleted, nothing from news will be deleted.
dev.mysql.com/doc/refman/5.0/en/delete.html , look at the examples of doing joins in DELETE statements :) Do a find for "For the first multiple-table syntax, only matching rows from the tables listed before the FROM clause are deleted. " on the page :)
Typically you would have to alias the Products table
whys that? they have different names? This is straight from the mysql documentation: DELETE FROM t1, t2 USING t1 INNER JOIN t2 INNER JOIN t3 WHERE t1.id=t2.id AND t2.id=t3.id; No aliases?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.