SQLite有多对多加入和分组

时间:2016-04-29 04:43:56

标签: android sqlite android-sqlite

对于多对多关系表,这是一种非常正常的设置。

  1. product列表和category列表。
  2. 每个product都属于(0,n) category
  3. 每个category都包含(0,n) product
  4. TABLES

    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  |
    

    CATEGORY表

    | id | name |
    =============
    | 1  |  c1  |
    | 2  |  c2  |
    | 3  |  c3  |
    

    PRODUCT_CATEGORY表

    | 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语句来实现?

    我尝试了以下查询,但结果并未反映出我想要的内容。

    JOIN QUERY语句

    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         |
    

    有人可以就如何实现这一目标提出建议吗?

2 个答案:

答案 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;