首页 > 解决方案 > 如何使用交叉连接查找行>列组合?[SQL]

问题描述

我想创建来自不同类别 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

标签: mysqlsqldatabasecombinationscross-join

解决方案


您可以使用 across 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。


推荐阅读