Mysql根据单个列中的唯一值限制返回结果的数量

时间:2013-10-24 23:27:43

标签: php mysql sql

我有三张桌子,

Product_to_categories   => contains two columns (Category_id, Product_id)
Product => contains a few columns (product_id, name, sku, ...)
categories => contains a few columns (category_id, name, ....)

我想得到一个结果集,前10个独特的category_id与产品表一起加入,一个类别可以分配许多产品,我想要退回一个类别中的所有产品,但我只想得到前8个类别的产品......

当前查询:

SELECT p2c.category_id, p.pname, c.category_name
FROM product p LEFT JOIN   product_to_category p2c
ON (p.product_id = p2c.product_id)
Left Join category c (p2c.category_id = c.category) LIMIT 0,8

当前输出

catID  |    p.name   |    catName |<br/>
1      |     docs    |      shoe<br/>
1      |     bob      |     shoe<br/>
1      |     mom      |     shoe<br/>
1      |     cat      |     shoe<br/>
1      |     dang     |     shoe<br/>
1      |     kit      |     shoe<br/>
2      |     pis      |     book<br/>
2      |     jiz      |     book<br/>

目前我只得到前8个结果无意义,但我希望获得以下输出:

catID  |    p.name   |    catName |<br/>
1      |     docs    |      shoe<br/>
1      |     bob      |     shoe<br/>
1      |     mom      |     shoe<br/>
1      |     cat      |     shoe<br/>
1      |     dang     |     shoe<br/>
1      |     kit      |     shoe<br/>
2      |     pis      |     book<br/>
2      |     jiz      |     book<br/>
3      |     docs     |     shirt<br/>
3      |     bob      |     shirt<br/>
3      |     mom      |     shirt<br/>
4      |     cat      |     light<br/>
4      |     dang     |     light<br/>
5      |     kit      |     sound<br/>
6      |     pis      |     mic<br/>
6      |     jiz      |     mic<br/>
7      |     docs     |     pen<br/>
7      |     bob      |     pen<br/>
7      |     mom      |     pen<br/>
7      |     cat      |     pen<br/>
8      |     dang     |     lace<br/>
8      |     kit      |     lace<br/>
8      |     pis      |     lace<br/>
8      |     jiz      |     lace<br/>

我希望结果集包含分配给前8个类别的所有产品的结果...

请指教。 谢谢 哈迪

1 个答案:

答案 0 :(得分:0)

我有点不确定为什么你的查询是从产品表开始的,所以我不打算 - 但除此之外,我认为你需要的是:

SELECT c.category_id, p.pname, c.category_name
FROM category c 
    INNER JOIN product_to_category pc ON c.category_id = pc.category_id
    INNER JOIN product p ON pc.product_id = p.product_id
WHERE c.category_id in (SELECT TOP 8 category_id FROM Category)
ORDER BY 1, 2