将所有结果作为一行返回

时间:2014-02-19 19:58:01

标签: sqlite

我正在使用Sqlite3,我对如何使用给定数据集构建字符串感到有点困惑。我想要的是从给定的项目中获取每个标记而不需要处理一堆行。

SELECT i.item, t.tag
    FROM items i 
    LEFT JOIN tags t
         ON i.id=t.item
    WHERE i.id=:id;

返回如下表格:

 | item6 | tag1 |
 | item6 | tag2 |

首选格式:

| item6 | tag1, tag2, tag3 |

1 个答案:

答案 0 :(得分:2)

使用group_concat

SELECT i.item,
       group_concat(t.tag)
FROM items AS i
LEFT JOIN tags AS t ON i.id = t.item
WHERE i.id = :id
GROUP BY i.item

对于像这样的小型查询,性能并不重要,但如果您认为连接和GROUP BY过度,请尝试以下方法:

SELECT item,
       (SELECT group_concat(tag)
        FROM tags
        WHERE item = :id)
FROM items
WHERE id = :id
相关问题