Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL join two tables without keys/relations

Tags:

sql

join

I have two tables, one of them has weeks of year, and the second table has categories. I need to create a table that contains each week and each category, but there's no fields/keys that intersect in two tables:

Table 1:

week1 week2 week3 week4 

Table 2:

Cat1 Cat2 

Resulting table:

week1 cat1 week1 cat2 week2 cat1 week2 cat2 ... week4 cat1 week4 cat2 

I'd like to do this without using many cursors/looping.

like image 882
dirol Avatar asked Nov 25 '09 15:11

dirol


People also ask

Can we join two tables without foreign key relation?

A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.

Can we join two tables without any relation SQL?

Yes, you can! The longer answer is yes, there are a few ways to combine two tables without a common column, including CROSS JOIN (Cartesian product) and UNION. The latter is technically not a join but can be handy for merging tables in SQL. In this article, I'll guide you through the different solutions with examples.


2 Answers

SELECT * FROM Table1 CROSS JOIN Table2 

This will get you every combination of all columns from Table1 and Table2.

like image 97
Matthew Jones Avatar answered Sep 23 '22 17:09

Matthew Jones


Have you tried just

 SELECT * FROM table1, table2 
like image 21
Valentin Golev Avatar answered Sep 23 '22 17:09

Valentin Golev