MySQL SELECT Duplicated rows from OpenCarts DataBa

2019-07-21 03:57发布

Just playing with OpenCarts DB to see if I can lear something. If I use the following SELECT the result returns duplicated rows:

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

Note that even using DISTINCT it is duplicated, but if I add an GROUP BY p.product_id it stops duplicating the rows. Is it the best solution?

1条回答
趁早两清
2楼-- · 2019-07-21 04:32

DISTINCT removes duplicate entire rows.

Use GROUP BY p.product_id to display one 1 row per product id.

Note: If you group by product_id, if you have multiple product description's, multiple categories, or multiple category description's The query will return a random row for each. Use the MIN() or MAX() functions to retrieve single ID's, or use the GROUP_CONCAT() function to retrieve all the description.

Example

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
查看更多
登录 后发表回答