如何在sqlite中将_concat子组与limit分组?
我有一张非常简单的桌子如何在sqlite中将_concat子组与limit分组?,sql,database,sqlite,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,但数量有限 例如,要使用2进行限制,它应该返回 id | nam
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,但数量有限
例如,要使用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的名称进行排序?在较新版本的SQLite中,您可以使用窗口函数:
select f.id, group_concat(b.name) as names
from foo join
(select b.*,
row_number() over (partition by b.id order by b.id) as seqnum
from bar b
) b
on b.id = f.id
where seqnum <= 2
group by f.id;
正如您对问题的措辞一样,连接不是必需的:
select b.id, group_concat(b.name) as names
from (select b.*,
row_number() over (partition by b.id order by b.id) as seqnum
from bar b
) b
where seqnum <= 2
group by b.id;
使用从另一个有限子查询获取连接的子查询应该可以工作
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;
共享输出Shample您的sqlite是什么版本的?遗憾的是,无法保证组_concat的值顺序。From:连接元素的顺序是任意的。
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;