SQL 按字母顺序对具有多对多关系的记录进行排序
SQL sort records which have many to many relations in alphabetical order
我有以下数据库表:COMMENT 和 TAG 和 COMMENT_TAG .它们之间是多对多的关系,实际上一个评论可以有多个标签,一个标签可以用于多个评论。让我们想象一下:
COMMENT
---------------
ID TEXT
1 comment1
2 comment2
3 comment3
4 comment4
TAG
---------------
ID NAME
1 bb
2 cc
3 ca
4 aa
5 ac
6 bd
COMMENT_TAG
---------------
ID_COMMENT ID_TAG
1 1
1 2
1 3
1 4
2 1
2 3
3 3
3 4
3 5
3 6
4 1
4 2
4 3
4 4
4 5
4 6
作为 FE 方面的结果,显示了以下数据
Comment Tags
==================================
comment1 bb, cc, ca, aa
comment2 bb, ca
comment3 ca, aa, ac, bd
comment4 bb, cc ,ca, aa, ac, bd
我想按以下方式排序:
1 按字母顺序对每个评论的标签进行排序:
Comment Tags
==================================
comment1 aa, bb, ca, cc
comment2 bb, ca
comment3 aa, ac, bd, ca
comment4 aa, ac, bb, bd, ca, cc
2 按标签按字母顺序对评论进行排序:
Comment Tags
==================================
comment4 aa, ac, bb, bd, ca, cc
comment3 aa, ac, bd, ca
comment1 aa, bb, ca, cc
comment2 bb, ca
您能否建议如何使用 SQL 实现它,或者建议一些针对此类用例的替代排序方法?
加入表格并按评论分组。
然后对 Oracle 11g+ 使用类似 LISTAGG()
的函数,连接每个评论的所有标签:
select c.text, listagg(t.name, ',') within group (order by t.name) tags
from "COMMENT" c
left join COMMENT_TAG ct on ct.id_comment = c.id
left join TAG t on t.id = ct.id_tag
group by c.id, c.text
为每个案例添加 ORDER BY
子句:
order by c.text
或:
order by tags
参见demo。
我有以下数据库表:COMMENT 和 TAG 和 COMMENT_TAG .它们之间是多对多的关系,实际上一个评论可以有多个标签,一个标签可以用于多个评论。让我们想象一下:
COMMENT
---------------
ID TEXT
1 comment1
2 comment2
3 comment3
4 comment4
TAG
---------------
ID NAME
1 bb
2 cc
3 ca
4 aa
5 ac
6 bd
COMMENT_TAG
---------------
ID_COMMENT ID_TAG
1 1
1 2
1 3
1 4
2 1
2 3
3 3
3 4
3 5
3 6
4 1
4 2
4 3
4 4
4 5
4 6
作为 FE 方面的结果,显示了以下数据
Comment Tags
==================================
comment1 bb, cc, ca, aa
comment2 bb, ca
comment3 ca, aa, ac, bd
comment4 bb, cc ,ca, aa, ac, bd
我想按以下方式排序:
1 按字母顺序对每个评论的标签进行排序:
Comment Tags
==================================
comment1 aa, bb, ca, cc
comment2 bb, ca
comment3 aa, ac, bd, ca
comment4 aa, ac, bb, bd, ca, cc
2 按标签按字母顺序对评论进行排序:
Comment Tags
==================================
comment4 aa, ac, bb, bd, ca, cc
comment3 aa, ac, bd, ca
comment1 aa, bb, ca, cc
comment2 bb, ca
您能否建议如何使用 SQL 实现它,或者建议一些针对此类用例的替代排序方法?
加入表格并按评论分组。
然后对 Oracle 11g+ 使用类似 LISTAGG()
的函数,连接每个评论的所有标签:
select c.text, listagg(t.name, ',') within group (order by t.name) tags
from "COMMENT" c
left join COMMENT_TAG ct on ct.id_comment = c.id
left join TAG t on t.id = ct.id_tag
group by c.id, c.text
为每个案例添加 ORDER BY
子句:
order by c.text
或:
order by tags
参见demo。