该组正在摆脱一些行?

时间:2011-11-02 16:30:20

标签: mysql group-by

我有这个查询

SELECT *, bp.product_id 
FROM builder_product as bp 
JOIN builder_step as bs 
    ON bs.builder_id=bp.builder_id  
JOIN builder as b 
    ON b.builder_id=bs.builder_id 
WHERE b.business_id = '60' 
GROUP BY product_id 
ORDER BY bs.step_number 

builder_product表中抓取所有产品,所有产品看起来都不错,但仔细看看数据缺少一些记录,所有名称都相同。

这是data and the schema,基本上我想要的是一个查询,它给我builder_product表中的所有产品以及builder_step表中{{1}的相应名称来自business_id的60。

任何想法我做错了什么以及如何避免重复?

2 个答案:

答案 0 :(得分:1)

从您的架构中不清楚builder_productbuilder_stepbuilder_id还是builder_step_id。如果你澄清我将修改下面的答案。

您没有执行任何汇总功能(SUM(), COUNT(), AVG()),因此您无需GROUP BY。相反,你只需要执行几个JOIN

SELECT
  bp.*,
  bs.name
FROM 
  builder_product bp
  JOIN builder_step bs ON bp.builder_step_id = bs.builder_step_id
  JOIN builder b ON bp.builder_id = b.builder_id
WHERE b.business_id = 60

重复项是在没有指定表名/别名的情况下尝试SELECT *的结果。相反,SELECT bp.*, bs.name表示应该返回builder_product中的所有列,以及builder_name中的builder_step列。

答案 1 :(得分:1)

您不应选择group by子句中未列出的行 MySQL允许这样做,但有一些pittfals 大多数其他SQL都会在您的查询中出错。

将其重写为:

SELECT bp.*, bs.*, b.* 
FROM FROM builder_product as bp
INNER JOIN builder_step as bs ON bs.builder_id=bp.builder_id  
INNER JOIN builder as b ON b.builder_id=bs.builder_id 
WHERE bp.product_id IN 
  (
  SELECT bp1.product_id 
  FROM builder_product as bp1 
  JOIN builder_step as bs1 ON bs1.builder_id = bp1.builder_id  
  JOIN builder as b1 ON b1.builder_id = bs1.builder_id 
  WHERE b1.business_id = '60' 
  GROUP BY bp1.product_id 
  )
  AND b.business_id = '60'
ORDER BY bs.step_number