How do I get all combinations of data from a MySQL table?

谁说胖子不能爱 提交于 2019-12-01 09:02:15

Given your table... I'm assuming you want every possible combo of value and option. That's a cross join (a join without any ON or where clause limiting the results):

 SELECT a.value_id, b.option_id 
     FROM assigned_options a 
     JOIN assigned_options b 
     GROUP BY a.value_id, b.option_id 

The group by filters out the duplicate results.

Do you have 2 other tables value and option that you want to pull all combinations of?

select option_id, value_id
from assigned_options
group by option_id, value_id
order by option_id, value_id

In TSQL you can use a recursive CTE, Can''t remember where I got it, but pretty sweet. Note MYSQL doesn't use "With" option, so it won't work in MySQL

WITH Numbers(N) AS (
                    SELECT N
                    FROM ( VALUES(1), (2), (3), (4), (5), (6)) Numbers(N)),
                        Recur(N,Combination) AS (
                        SELECT N, CAST(N AS VARCHAR(20)) 
                        FROM Numbers


UNION ALL

SELECT n.N,CAST(r.Combination + ',' + CAST(n.N AS VARCHAR(10)) AS VARCHAR(20)) 
FROM Recur r
INNER JOIN Numbers n ON n.N > r.N)



select Combination
from RECUR
ORDER BY LEN(Combination),Combination;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!