HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

Can I generate a list of all combinations between two columns

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
cancolumnsallcombinationsgeneratebetweentwolist

Problem

table 1
|id|name  |
------------
|1 |Bob   |
|2 |Frank |
|3 |Paula |

Table 2
|id|item|
---------
|1 |a   |
|2 |b   |
|3 |c   |


i need to write a query to show me all the combinations of the two tables as below:

result
|name|item|
-----------
|bob |a   |
|bob |b   |
|bob |c   |
etc


I am currently using mysql any help would be greatly appreciated

Solution

This is called a cartesian product or a CROSS JOIN:

SELECT 
    a.name,  b.item 
FROM 
    table1 AS a 
  CROSS JOIN 
    table2 AS b;

Code Snippets

SELECT 
    a.name,  b.item 
FROM 
    table1 AS a 
  CROSS JOIN 
    table2 AS b;

Context

StackExchange Database Administrators Q#145874, answer score: 14

Revisions (0)

No revisions yet.