我有这个非常简单的表
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');
我想为每个bar.name
连接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
但是我不知道如何限制name
到group_concat的范围。
我还如何订购name
过去的group_concat
?
答案 0 :(得分:1)
在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;
如果只需要两个值,也许min()
和max()
会满足您的要求:
select f.id,
(case when min(b.name) = max(b.name)
then min(b.name)
else min(b.name) || ',' || max(b.name)
end) as names
from foo join
bar b
on b.id = f.id
group by f.id;
正如您所说的那样,join
不是必需的:
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;
答案 1 :(得分:0)
使用一个子查询,该子查询可以从另一个有限的子查询中获取连接。
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;