如何使用连接从不同的表中获取唯一行

时间:2014-08-19 10:54:45

标签: mysql sql join

我有一个查询,其中从不同的产品表中获取结果。对于单个产品,有不同的类别。

    select    p.model as model,
              pd.name as product_name,
              p.price as price,
              c.category_id as category,
              p.weight as weight, 
              pd.description as description,
              p.image as image 

    from      ares_product p 
    join      ares_product_description pd on p.product_id = pd.product_id 
    join      ares_product_to_category c on p.product_id =c.product_id 
    order     by p.product_id.

通过使用此查询获得结果,如

-RXR16 Rain-X Repel 16" 10.0000 30 7.00000000 Rain-X Repel 16" data/newimages/Repel.jpg

-RXR16 Rain-X Repel 16" 10.0000 34 7.00000000 Rain-X Repel 16" data/newimages/Repel.jpg

为此产品相同,但类别不同。

我如何在一个结果中获得它们,如

-RXR16 Rain-X Repel 16" 10.0000 30,34 7.00000000 Rain-X Repel 16" data/newimages/Repel.jpg

1 个答案:

答案 0 :(得分:1)

SELECT
    p.model as model,
    pd.name as product_name,
    p.price as price,
    GROUP_CONCAT(c.category_id) as category,
    p.weight as weight,
    pd.description as description,
    p.image as image
FROM ares_product p
JOIN ares_product_description pd
    ON p.product_id = pd.product_id
JOIN ares_product_to_category c
    ON p.product_id = c.product_id
GROUP BY p.product_id
ORDER BY p.product_id

使用GROUP_CONCATGROUP BY子句,您可以获得所需的结果。