1

我有三张桌子,

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 个类别的所有产品的结果...

请指教。谢谢哈迪

4

1 回答 1

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
于 2013-10-25T01:48:12.677 回答