Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql select/delete using join over four tables

I have four tables (in [] are columns):

users [id]

products [id]

productRatings [id,value,user,product]

comments [id,product,user]

I would like to select/and ultimately delete productRatings where there are no associated comment by the same user for that product. That is, if user has rated product but did not comment, that rating should be deleted.

I believe I could achieve that by using two queries, first:

SELECT user, product FROM productRatings

and then for each row:

    SELECT COUNT(*) FROM comments WHERE product=productRatings.product AND user=productRatings.user

and then something like

    if $queryAbove==0 : DELETE FROM productRatings WHERE id=productRatings.id

I would like to solve this via JOIN and learn more by example rather than dig through JOIN tutorials.

like image 493
dbr Avatar asked Apr 22 '15 13:04

dbr


People also ask

How do you delete data using join in MySQL?

MySQL DELETE JOIN with LEFT JOIN We can also use the LEFT JOIN clause in the DELETE statement to delete rows in a table (left table) that does not have matching rows in another table (right table). Note that we only put T1 table after the DELETE keyword, not both T1 and T2 tables like we did with the INNER JOIN clause.

Can we use JOIN IN delete query MySQL?

The Inner Join query can be used with Delete query for removing rows from one table and the matching rows from the other table that fulfill the specified condition.

How do you use delete with join?

The following are the basic syntax of Delete Join with its parameters. The different parameters used in the syntax are: DELETE t1: It is used to delete the required table from the database. Here, you may choose from the first table's instance t1 and the second table's instance t2.


1 Answers

You only need the productratings and comments table - the following works:

delete pr
from productratings pr
left join comments c
  on pr.userid = c.userid
  and pr.productid = c.productid
where c.productid is null

And there's a demo here: http://sqlfiddle.com/#!9/89575/1

like image 110
pala_ Avatar answered Oct 11 '22 21:10

pala_