如何在SQLite中折叠结果集?

时间:2015-02-03 18:19:34

标签: sql sqlite

假设我有桌子

id name
1  nora
2  mars
3  ven

我在这张桌子上加入了id

id type     value
1  clothing shirt
1  clothing pants
1  toys     abacus
1  toys     legos
      ...

我如何制作看起来像的东西,

id name   clothing       toys
1  nora   shirt, pants   abacus, legos 

1 个答案:

答案 0 :(得分:2)

如果要将不同的值放入不同的结果列,则简单连接无效。 您需要使用相关子查询:

SELECT id,
       name,
       (SELECT group_concat(value, ', ')
        FROM Table2
        WHERE id = Table1.id
          AND type = 'clothing'
       ) AS clothing,
       (SELECT group_concat(value, ', ')
        FROM Table2
        WHERE id = Table1.id
          AND type = 'toys'
       ) AS toys
FROM Table1