My problem is I want to delete records from two tables, deleting the records that are a result of the following query:
SELECT AVG(pr.rating) AS rating_average
FROM products p
INNER JOIN product_ratings pr
ON pr.product_id = p.product_id
GROUP BY p.product_id
HAVING AVG(pr.rating) < 3
The above query shows average ratings of a product that are less than 3, I want to delete products and their associated ratings of all the results from the above query.
I looked at DELETE FROM product_ratings, products WHERE EXISTS (//above query), but this didn’t work, I’ve been trying various DELETE statements to no avail.
I have read the following, and still cannot find a solution: SQL: DELETE Statement & SQL: EXISTS Condition.
The tables are products and product_ratings, with the following structure:
products
--------
product_id [PK] | link | ...
product_ratings
---------------
rating_id [PK] | rating | product_id
Appreciate any help, as well as links to reference material to better understand how it’s done.
EDIT: Apologies for not stating what RDBMS I’m using, It’s MySQL
EDIT2: A bit confused now, @Martin’s example doesn’t use a temp table like the other answers, I assume this is because of my vague question not stating with RDBMS I was using?
You have now added the
MySQLtag. In that case this might do the job for you.MySQL does support a multiple table DELETE syntax. The derived table is to get around the issue where it doesn’t allow mutating (update or delete target) tables to be referenced in a sub query (it materializes the result into a temporary table).