mysql - 如何使用交叉连接查找行>列组合?[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
解决方案
您可以使用 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。
推荐阅读
- android - 反应原生开始
- d3.js - 为什么 Babel 7 对一无所知的浏览器使用 require() 函数?
- javascript - 使用 Knockout.js(ES6 语法)初始化谷歌地图
- android - AppWidget 在多个设备中停止工作
- android - 如何将文件复制到 Android 模拟器以用于仪器测试?
- html - HTML下拉移动一切
- r - 在R中的循环中绑定表
- javascript - css - 透明图像的动画背景
- javascript - JavaScript,HTML,没有 JQuery - 如何在句子中间添加包含链接的字符串?
- logging - 如何使用 JOIN 解决 Kusto 的区分大小写问题