使用四个表

时间:2015-04-22 13:50:59

标签: php mysql join multiple-tables

我有四个表(在[]中是列):

$(document).ready(function(){ $("#selectStores").change(function(){ $('.businessSpecifics').remove(); var number=$("#selectStores option:selected").text(); var htmlToInsert=""; for(var i=1;i<=number;i++) { htmlToInsert='<div class="businessSpecifics">' +'<label>URL Extension '+i+':</label>' +'<br> <input form="form'+i+'" type="text" name="urlExtension" placeholder="businessname" id="businessSpecificsURL" class="businessSpecifics details" />' +'<span>.byMyCompany.com</span>' +'<br><label>Login Email '+i+':</label>' +'<br><input form=form="form'+i+'" type="email" name="email" placeholder="email" id="businessSpecificsEmail" class="businessSpecifics details" />' +'<br><label>Password '+i+':</label>' +'<br><input form=form="form'+i+'" type="password" name="tempPswd" placeholder="" class="businessSpecificsdetails "/>' +'<br><label>Business Website '+i+':</label>' +'<br><input form=form="form'+i+'" type="text" name="bussinessWebsite" placeholder="Business Website" class="businessSpecifics details" />' +'</div><br/><br/>'; $(htmlToInsert).insertAfter("#selectStores"); } }); });

users [id]

products [id]

productRatings [id,value,user,product]

我想选择/并最终删除productRatings,其中该产品的同一用户没有相关评论。也就是说,如果用户对产品进行了评级但未发表评论,则应删除该评级。

我相信我可以通过使用两个查询来实现这一点,首先:

comments [id,product,user]

然后每行:

SELECT user, product FROM productRatings

然后像

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

我想通过JOIN解决这个问题,并通过示例了解更多信息,而不是通过JOIN教程进行深入研究。

4 个答案:

答案 0 :(得分:4)

您只需要产品和评论表 - 以下作品:

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

这里有一个演示:http://sqlfiddle.com/#!9/89575/1

答案 1 :(得分:2)

DELETE FROM `productRatings` WHERE productRatings.id NOT IN (
SELECT productRatings.id FROM `productRatings` JOIN `comments` ON productRatings.user = comments.user AND productRatings.product = comments.product )

我要制作相关表格的副本,并在生产表格上使用之前测试上述内容是否适用于测试表。

基本上,嵌套选择将返回写入评级的用户也发表评论的所有productRatings id。使用NOT IN,它会删除评分用户也没有评论的所有评分。

由于pala_在下面的注释中突出显示,因为此方法使用嵌套的sql,它将比仅在较大的表上使用连接的方法执行得更糟。

答案 2 :(得分:1)

您应该能够加入查询中的字段,然后检查评论是否为空,如此...

DELETE FROM `productRatings` 
JOIN `comments` ON (`productRatings`.`product` = `comments`.`product`)
WHERE `comments`.`comment_field` IS NULL
AND `productRatings`.`user_id` = ?;

根据您使用的数据库引擎,IS NULL可能需要替换为=''。

请记住首先测试数据库的测试实例!

答案 3 :(得分:0)

  DELETE FROM productRatings WHERE id IN (SELECT pr.id FROM productRatings pr
      LEFT JOIN comments c on c.product = pr.product
      WHERE c.user = pr.user
      AND pr.comment IS NULL)