如何选择所需的记录?

时间:2010-12-26 23:17:41

标签: sql mysql doctrine

表:

  • 产品:[id,name,brand_id,is_published]
  • 品牌:[id,name,is_published]
  • 奖项:[id,name]
  • ProductAwards [product_id,award_id]

如何选择PUBLISHED品牌列表以及已发布品牌产品的AWARDS数量。

除了在计算奖励时发出“is_published”限制外,我对所有部分感到很满意。

我希望这很清楚;任何人都可以建议在哪里挖掘?

5 个答案:

答案 0 :(得分:1)

我猜这是你正在寻找的查询:

SELECT Brand.name, COUNT(Awards.id) AS Awards
FROM Brand
LEFT JOIN Product ON product.brand_id = Brand.id AND Product.is_published = TRUE /* This may need to be changed based on the data type of is_published */
LEFT JOIN ProductAwards ON ProductAwards.product_id = Product.id
LEFT JOIN Awards ON Awards.id = ProductAwards.award_id
WHERE Brand.is_published = TRUE /* As with Product.is_published, this clause is dependent on the column's data type */

要获得更明智的答案,您可能希望为每个表发布SHOW CREATE TABLE的结果,以及您要查找的结果类型的示例。希望这有帮助!

答案 1 :(得分:1)

SELECT b.name, count(pa.award_id) as Quantity
FROM PRODUCT p 
      LEFT JOIN Brand b ON p.brand_id = b.id
      LEFT JOIN ProductAwards pa on p.Product_id = pa.product_id
      LEFT JOIN Awards a ON a.award_id = pa.award_id
WHERE p.is_published = 1
GROUP BY b.name

这样的东西?

答案 2 :(得分:1)

假设强制执行参照完整性,因此ProductAwards表中没有错误的条目,您实际上不需要从奖励表中进行选择:

SELECT B.Name, COUNT(PA.Award_ID) AS Num_Awards
  FROM Brand              AS B
  LEFT JOIN Product       AS P  ON P.Brand_ID = B.ID AND P.Is_Published = TRUE
  LEFT JOIN ProductAwards AS PA ON PA.Product_ID = P.ID
 WHERE B.Is_Published = TRUE

如果某个品牌没有奖励,则COUNT(PA.Award_ID)将返回零,因为COUNT(列)计算非空值的数量。

答案 3 :(得分:0)

如果你有一个查询(如果我正确地阅读了问题)除了已发布的限制之外100%工作,那么这个限制是微不足道的 - 只需将AND is_published = 1添加到WHERE子句中(或添加WHERE is_published = 1如果你的查询没有WHERE子句。)

以上假设is_published是一个包含0或1的整数,用于非发布或已发布。如果列不同,则需要相应地更改表达式。

答案 4 :(得分:0)

您可以尝试此查询以获取每个品牌ID所需的计数

SELECT b1.id, COUNT(pa.award_id) [No of awards]
FROM Brand1 b1 left join Product p
ON p.brand_id=b1.id AND p.is_published=1 AND b1.is_published=1
LEFT JOIN ProductAwards pa
ON pa.product_id = p.id
LEFT JOIN Awards a
ON a.id=pa.award_id
GROUP BY b1.id