Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join 2 tables without common column?

Tags:

join

select

mysql

i have 2 tables

User Code         SubMenuID

usercol           menucol 
-----------       -------------
AB                Sub-01 
Alam              Sub-02 
CSRL

i want to show them like this

usercol           menucol
----------        ------------
AB                Sub-01 
AB                Sub-02 
Alam              Sub-01
Alam              Sub-02 
CSRL              Sub-01 
CSRL              Sub-02

How can i get this using sql query? It would be very helpful :)

like image 983
Anupam Roy Avatar asked Nov 29 '12 07:11

Anupam Roy


People also ask

How do you join two tables without common columns?

One way to join two tables without a common column is to use an obsolete syntax for joining tables. With this syntax, we simply list the tables that we want to join in the FROM clause then use a WHERE clause to add joining conditions if necessary.

Can we use join without common column?

There are few ways to combine the two tables without a common column including Cross Join (Cartesian Product) and UNION. This is not a join but can be useful for merging tables in SQL.

Can you join two tables with different columns?

Merging tables by columns. Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other).


1 Answers

Since the tables are not related by a foreign key relationship, you can not join them - what you want as a result, is the Cartesian product from the two tables. This is achieved by selecting from both tables without any additional join condition (this is also called a cross join):

mysql> SELECT * FROM userCode, SubMenuId;

This query combines all rows from the first table with all rows from the second table.

+---------+---------+
| usercol | menucol |
+---------+---------+
| AB      | Sub-01  |
| AB      | Sub-02  |
| Alam    | Sub-01  |
| Alam    | Sub-02  |
| CSRL    | Sub-01  |
| CSRL    | Sub-02  |
+---------+---------+
like image 138
Andreas Fester Avatar answered Oct 03 '22 02:10

Andreas Fester