1

I have 3 tables

Table1:         Table2:       Table3:     
**Users**       **Posts**     **Articles**

Name|           Title|        Title|
Raj             Post1         Article1
Sujay           Post2         Article2
Bijay           Post3         Article3
Jijay           Post4         Article4

Now I want to do combine all possible combination of them and put it into another table

Like I want to put it in a table tmp_all_cobinations

Table: **tmp_all_combinations**

Name
Raj.Post1.Aticle1
Raj.Post1.Aticle2
Raj.Post1.Aticle3
Raj.Post1.Aticle4
Raj.Post2.Aticle1
...
Raj.Post3.Aticle1
....
Sujay.

....

in this way

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74

3 Answers3

4

Do a cross join between the three tables, which in MySQL can be achieved by doing an INNER JOIN with no ON restriction.

INSERT INTO tmp_all_combinations (Users, Posts, Articles)
SELECT t1.Users, t2.Posts, t3.Articles
FROM Table1 t1
INNER JOIN Table2 t2
INNER JOIN Table3 t3

If you are using Postgres, then you can replace INNER JOIN with CROSS JOIN to get the same result.

If the tmp_all_combinations does not already exist, you can create it, making sure the columns have the same types as the three source tables.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 3
    @RajarshiDas I am OK, but no one is as good as [this guy](http://stackoverflow.com/users/1144035/gordon-linoff) when it comes to writing SQL queries. – Tim Biegeleisen Jul 30 '16 at 11:24
1

The ANSI-SQL way to address this would be to use a cross join:

INSERT INTO tmp_all_combinations
SELECT      table1.name, table2.title, table3.title
FROM        table1
CROSS JOIN  table2
CROSS JOIN  table3
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Basically what you need is a join without any columns to join on, so it will be all columns on all columns. so it's simply:

select * from users, Posts, articles
spiderman
  • 289
  • 3
  • 15