Skip to content
Advertisement

Retrieving all combinations from a database table with alternative values

Say we have a simple DB-table tab created in MySql with

JavaScript

and filled with an examplary set of data:

JavaScript

Each row has a value val and for id=2,4 an alternative value altval. Is there a way in SQL to retrieve all combinations for abitrary data sets? (The number of combinations is 2 power the number of rows with alternative datasets, here: 4, therefore ‘abitrary’ is of course limited.) For the given example, the result should be: (1,2,4,5),(1,2,4,6),(1,3,4,5),(1,3,4,6)

In a script language like php, I would solve this problem by generating nested for-loops using eval().

Advertisement

Answer

Using recursive CTE:

JavaScript

db<>fiddle demo

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement