How can we write MySQL query for cross joins with the help of Comma operator?


Writing cross joins with the help of comma operator is the most basic way to combine two tables. As we know that we can also write cross join by using keyword CROSS JOIN or synonyms like JOIN. To form a cross join we do not need to specify the condition which is known as join-predicate To understand it, we are taking the example of two tables named tbl_1 and tbl_2 which are having following data −

mysql> Select * from tbl_1;
+----+--------+
| Id | Name   |
+----+--------+
| 1  | Gaurav |
| 2  | Rahul  |
| 3  | Raman  |
| 4  | Aarav  |
+----+--------+
4 rows in set (0.00 sec)

mysql> Select * from tbl_2;
+----+---------+
| Id | Name    |
+----+---------+
| A  | Aarav   |
| B  | Mohan   |
| C  | Jai     |
| D  | Harshit |
+----+---------+
4 rows in set (0.00 sec)

Now, the query below will cross join the above-mentioned tables with comma operator −

mysql> Select * FROM tbl_1,tbl_2 ;
+----+--------+----+---------+
| Id | Name   | Id | Name    |
+----+--------+----+---------+
| 1  | Gaurav | A  | Aarav   |
| 2  | Rahul  | A  | Aarav   |
| 3  | Raman  | A  | Aarav   |
| 4  | Aarav  | A  | Aarav   |
| 1  | Gaurav | B  | Mohan   |
| 2  | Rahul  | B  | Mohan   |
| 3  | Raman  | B  | Mohan   |
| 4  | Aarav  | B  | Mohan   |
| 1  | Gaurav | C  | Jai     |
| 2  | Rahul  | C  | Jai     |
| 3  | Raman  | C  | Jai     |
| 4  | Aarav  | C  | Jai     |
| 1  | Gaurav | D  | Harshit |
| 2  | Rahul  | D  | Harshit |
| 3  | Raman  | D  | Harshit |
| 4  | Aarav  | D  | Harshit |
+----+--------+----+---------+
16 rows in set (0.00 sec)

Updated on: 20-Jun-2020

98 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements