从多个重复项中仅选择一个记录

时间:2015-02-06 11:08:13

标签: mysql sql

您好我使用以下查询从数据库中选择一些元素。

SELECT *,c.slug AS pslug,d.slug AS catslug 
FROM uhhu_virtuemart_products as a 
LEFT JOIN uhhu_virtuemart_products_el_gr as d 
    on a.virtuemart_product_id=d.virtuemart_product_id 
LEFT JOIN uhhu_virtuemart_product_categories as b 
    ON a.virtuemart_product_id = b.virtuemart_product_id 
LEFT JOIN uhhu_virtuemart_categories_el_gr AS c 
    ON b.virtuemart_category_id=c.virtuemart_category_id 
WHERE a.virtuemart_product_id = 508

问题是产品可以有多个类别,所以这个查询返回3行,而我需要总是输出1行。

virtuemart_product_categories: Product_categories_table

我想要的是,当它在这里检查类别时:

LEFT JOIN uhhu_virtuemart_product_categories as b ON a.virtuemart_product_id = b.virtuemart_product_id 发出LIMIT 1声明

我尝试使用这样的嵌套选择:

SELECT *,c.slug AS pslug,d.slug AS catslug
FROM uhhu_virtuemart_products as a 
WHERE uhhu_virtuemart_product_id =
    (SELECT virtuemart_product_id 
    from virtuemart_product_categories 
    where virtuemart_product_id=508 LIMIT 1)
LEFT JOIN uhhu_virtuemart_categories_el_gr AS c 
ON a.virtuemart_category_id=c.virtuemart_category_id
LEFT JOIN uhhu_virtuemart_categories_el_gr as d 
on c.virtuemart_category_id=d.virtuemart_category_id

就像这样:

   SELECT *,c.slug AS pslug,d.slug AS catslug 
FROM uhhu_virtuemart_product_categories as a
LEFT JOIN uhhu_virtuemart_products_el_gr as d 
on a.virtuemart_product_id=d.virtuemart_product_id 
LEFT JOIN uhhu_virtuemart_categories_el_gr AS c 
ON a.virtuemart_category_id=c.virtuemart_category_id 
WHERE a.virtuemart_product_id =( 
    SELECT virtuemart_product_id 
    from uhhu_virtuemart_product_categories as f 
    where f.virtuemart_product_id=508 
    LIMIT 1)

我也试过使用SELECT distinct但它也没有用。我只知道SQL的基础知识并且找不到类似的东西来帮助我解决这个问题,所以我将非常感谢你的帮助。

希望我很清楚。

0 个答案:

没有答案