MySQL 左联接无法在单个查询中删除重复项
MySQL Left join cannot remove duplicates in a single query
我有 2 个表:
产品:
- id
- name
product_images:
- id
- image
- product_id
我正在执行以下查询:
SELECT p.*, i.image
FROM products p
LEFT JOIN product_images i
ON p.id = i.product_id`
ORDER BY created_at DESC
但是,如果产品有几张图片,则此产品行会重复。我如何通过仅显示一对 p.id = i.product_id
中的第一个匹配项来删除这些重复项
对于这个数据集,简单的聚合应该可以做到:
SELECT p.*, min(i.image)
FROM products p
LEFT JOIN product_images i ON p.id = i.product_id
GROUP BY <enumerate all columns from products here>
ORDER BY created_at DESC
LIMIT ${limit}
如果您想要product_images
中的更多列,那么您也可以使用相关子查询进行过滤;假设 product_images
有主键 id
,它看起来像:
SELECT p.*, i.image
FROM products p
LEFT JOIN product_images i
ON i.id = (SELECT MIN(i1.id) FROM product_images i1 WHERE i1.product_id = p.id)
ORDER BY created_at DESC
LIMIT ${limit}
如果image
的数据类型是varchar或int,那么不加入table product_images
,而是加入每个产品图像的MIN:
SELECT p.*, i.image
FROM products p
LEFT JOIN (
SELECT product_id, MIN(image) image
FROM product_images
GROUP BY product_id
) i
ON p.id = i.product_id
ORDER BY created_at DESC
LIMIT ${limit}
我有 2 个表:
产品:
- id
- name
product_images:
- id
- image
- product_id
我正在执行以下查询:
SELECT p.*, i.image
FROM products p
LEFT JOIN product_images i
ON p.id = i.product_id`
ORDER BY created_at DESC
但是,如果产品有几张图片,则此产品行会重复。我如何通过仅显示一对 p.id = i.product_id
对于这个数据集,简单的聚合应该可以做到:
SELECT p.*, min(i.image)
FROM products p
LEFT JOIN product_images i ON p.id = i.product_id
GROUP BY <enumerate all columns from products here>
ORDER BY created_at DESC
LIMIT ${limit}
如果您想要product_images
中的更多列,那么您也可以使用相关子查询进行过滤;假设 product_images
有主键 id
,它看起来像:
SELECT p.*, i.image
FROM products p
LEFT JOIN product_images i
ON i.id = (SELECT MIN(i1.id) FROM product_images i1 WHERE i1.product_id = p.id)
ORDER BY created_at DESC
LIMIT ${limit}
如果image
的数据类型是varchar或int,那么不加入table product_images
,而是加入每个产品图像的MIN:
SELECT p.*, i.image
FROM products p
LEFT JOIN (
SELECT product_id, MIN(image) image
FROM product_images
GROUP BY product_id
) i
ON p.id = i.product_id
ORDER BY created_at DESC
LIMIT ${limit}