mysql多个连接并从两个内连接表中只检索一条记录

时间:2014-05-06 17:48:23

标签: mysql sql

我陷入了疑问。这是我当前的查询。

SELECT products.product_id, products.product_title,
    package_category_products.PCP_id,
    product_images.PI_file_name
FROM package_category_products
LEFT JOIN products ON products.product_id = package_category_products.PCP_product_id

-- BEGIN MARKED CODE
LEFT JOIN product_inventories on product_inventories.PI_product_id = products.product_id
INNER JOIN product_images on product_images.PI_product_id = product_inventories.PI_product_id
    AND product_images.PI_color = product_inventories.PI_color_id
-- END MARKED CODE

WHERE PCP_package_id = 17
AND PCP_package_category_id = 3
AND product_status ='active'  

此查询当前返回冗余数据。我想在标记的代码上使用子查询,在加入后只从这两个表中返回一条记录。这样我就可以避免冗余数据,并注意每个产品只需要一条记录。

1 个答案:

答案 0 :(得分:1)

将“SELECT”替换为“SELECT DISTINCT”:

SELECT DISTINCT a.product_id, a.product_title, d.PCP_id, c.PI_file_name

FROM package_category_products as d
LEFT JOIN products as a
ON a.product_id = d.PCP_product_id 

LEFT JOIN product_inventories as b on b.PI_product_id = a.product_id 

INNER JOIN product_images  as c
ON c.PI_product_id = b.PI_product_id AND c.PI_color = b.PI_color_id

WHERE PCP_package_id = 17 AND PCP_package_category_id = 3 AND product_status ='active'