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

后端 未结 3 906
长情又很酷
长情又很酷 2021-01-14 07:05

I have spent the last five hours trying to get every product option combination from a table but I\'m totally stuck now. I have a table with data like (simplified):

3条回答
  •  独厮守ぢ
    2021-01-14 07:47

    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;
    

提交回复
热议问题