sql - 如何在 sqlite 中限制 group_concat 子组?

标签 sql database sqlite

我有这个非常简单的表格

create table foo (id int);
create table bar (id int, name text);

insert into foo(id) values (1), (2);
insert into bar(id, name) values (1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e');

我想为每个 foo 连接 bar.name,但 bar.name 的数量有限。

比如限制为2,应该返回

id | names
1  | a,b
2  | c,d

没有限制,我知道我可以这样写

select id, group_concat(name) as names from foo natural join bar group by id;

它只是给了我

id | names
1  | a,b
2  | c,d,e

但我不知道如何限制通过 group_concat 的 name

另外,我如何订购经过 group_concatname

最佳答案

使用子查询,从另一个有限的子查询中获取串联应该可行。

SELECT f.id,
       (SELECT group_concat(x.name)
               FROM (SELECT b.name
                            FROM bar b
                            WHERE b.id = f.id
                            ORDER BY b.name
                            LIMIT 2) x) names
      FROM foo f;

db<>fiddle

关于sql - 如何在 sqlite 中限制 group_concat 子组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441803/

相关文章:

iphone - iphone应用程序会保留sqlite数据库吗

java - 使用 "StringUtils.join(array, "' ,'") 进行选择;"

c# - 更新大型SQLite数据库

SQL:带有参数的WITH子句?

mysql - 简单的子查询会在巨大的表上减慢速度

mysql - 为什么这个 MySQL 查询返回两行?

sql - 组合 COUNT 个查询

json - 如何使用 Oracle 数据库作为 JSON 的 Web 服务提供者?

python - 使用 python 在 SQLite 数据库中重复写入数据

mysql - 按一年中的周查找 ActiveRecord 对象