MySQL SELECT来自OpenCarts DataBase的重复行

时间:2011-02-15 01:39:07

标签: mysql select duplicates row

只是玩OpenCarts DB,看看我是否能学到一些东西。 如果我使用以下 SELECT ,结果将返回重复的行:

SELECT DISTINCT
p.product_id AS pid,
p.model AS modelo,
SUBSTRING(p.model,1,25) AS substr_modelo,
p.image AS foto,
p.price AS preco,
pd.name AS nome,
cd.name AS category
FROM product p
LEFT JOIN product_description pd ON p.product_id = pd.product_id
LEFT JOIN product_to_category p2c ON p.product_id = p2c.product_id
LEFT JOIN category_description cd ON p2c.category_id = cd.category_id
WHERE pd.name LIKE _utf8 'laser%' collate utf8_unicode_ci
ORDER BY p.product_id DESC

请注意,即使使用 DISTINCT 也会重复,但如果我添加 GROUP BY p.product_id ,则会停止重复行。这是最好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

DISTINCT删除重复的整行

使用GROUP BY p.product_id为每个产品ID显示一行。

注意:如果按product_id分组,如果您有多个产品说明,多个类别或多个类别说明,则查询将为每个类别返回一个随机行。使用MIN()MAX()函数检索单个ID,或使用GROUP_CONCAT()函数检索所有说明。

实施例

SELECT
  p.product_id AS pid,
  p.model AS modelo,
  SUBSTRING(p.model,1,25) AS substr_modelo,
  p.image AS foto,
  p.price AS preco,
  GROUP_CONCAT(pd.name) AS nome,
  GROUP_CONCAT(cd.name) AS category
FROM product p
  LEFT JOIN product_description pd ON p.product_id = pd.product_id
  LEFT JOIN product_to_category p2c ON p.product_id = p2c.product_id
  LEFT JOIN category_description cd ON p2c.category_id = cd.category_id
  WHERE pd.name LIKE _utf8 'laser%' collate utf8_unicode_ci
GROUP BY p.product_id
ORDER BY p.product_id DESC