对于多对多关系表,这是一种非常正常的设置。
product
列表和category
列表。product
都属于(0,n)
category
。category
都包含(0,n)
product
。CREATE TABLE product (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL);
CREATE TABLE category (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL);
CREATE TABLE product_category (
product_id INTEGER NOT NULL,
category_id INTEGER NOT NULL);
| id | name |
=============
| 1 | p1 |
| 2 | p2 |
| 3 | p3 |
| id | name |
=============
| 1 | c1 |
| 2 | c2 |
| 3 | c3 |
| product_id | category_id |
============================
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
| 3 | 1 |
我想知道如何按product
查询category_id
,并列出product
所有category_id
。
例如,我想查询 category = 1 中可用的产品列表,结果必须包含categories_id
所有类别必须列出product
所属的名称。
| product_id | product_name | categories_id |
=============================================
| 1 | p1 | 1,2,3 |
| 2 | p2 | 1,2 |
| 3 | p3 | 1 |
我知道这可以通过子查询来完成,但我想知道这是否可以通过JOIN
语句来实现?
我尝试了以下查询,但结果并未反映出我想要的内容。
SELECT
P.id AS product_id,
P.name AS product_name,
GROUP_CONCAT(PC.category_id, ',') AS categories_id
FROM product AS P
LEFT JOIN product_category AS PC
ON P.id = PC.product_id
WHERE PC.category_id = 1
GROUP BY P.id;
| product_id | product_name | categories_id |
=============================================
| 1 | p1 | 1 |
| 2 | p2 | 1 |
| 3 | p3 | 1 |
有人可以就如何实现这一目标提出建议吗?
答案 0 :(得分:1)
执行和查询的SqlFiddle是
SELECT P.id AS product_id, P.name AS product_name,
GROUP_CONCAT(PC2.category_id) AS categories_id
FROM
product AS P LEFT JOIN product_category AS PC ON
P.id = PC.product_id LEFT JOIN product_category AS PC2 ON
P.id = PC2.product_id
WHERE PC.category_id = 1
GROUP BY P.id;
答案 1 :(得分:0)
SELECT
p.id,
p.name,
GROUP_CONCAT(pc2.category_id, ',')
FROM product_category pc1
JOIN product_category pc2
JOIN product p
WHERE pc1.category_id = 1
AND pc1.product_id = pc2.product_id
AND p.id = pc1.product_id
GROUP BY pc1.product_id;