我想创建来自不同类别ID的项目组合。
你能帮助我吗?
表
+---------+-------------+------------+ | post_id | category_id | post_title | +---------+-------------+------------+ | 1 | 1 | Red | | 2 | 1 | Black | | 3 | 2 | Medium | | 4 | 3 | Male | | 5 | 3 | Female | +---------+-------------+------------+
我想要的查询结果如下:
Red-Medium-Male Black-Medium-Male Red-Medium-Female Black-Medium-Female
例如,如果存在属于6个不同类别的项目,则如下所示:
Red-Medium-Male-Other1-Other2-Other3
您可以使用cross join和过滤:
cross join
select t1.post_title, t2.post_title, t3.post_title from t t1 cross join t t2 cross join t t3 where t1.category_id = 1 and t2.category_id = 2 and t3.category_id = 3;
您可以使用递归CTE对此进行概括:
with recursive tt as ( select t.*, dense_rank() over (order by category_id) as cat_seqnum from t ), cte as ( select cat_seqnum, post_title from tt where cat_seqnum = 1 union all select tt.cat_seqnum, concat_ws('-', cte.post_title, tt.post_title) from cte join tt on tt.cat_seqnum = cte.cat_seqnum + 1 ) select * from cte where cat_seqnum = (select max(cat_seqnum) from tt);
这是一个db <> fiddle。