- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to apply CROSS JOIN correctly in MySQL?
The CROSS JOIN in MySQL returns the Cartesian product of rows from the joined tables. Let us see an example by creating a table −
mysql> create table PairDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(20), -> UserRelationshipName varchar(20) -> ); Query OK, 0 rows affected (0.56 sec)
Example
Insert some records in the table using insert command. The query is as follows −
mysql> insert into PairDemo(UserName,UserRelationshipName) values('John','James'); Query OK, 1 row affected (0.15 sec) mysql> insert into PairDemo(UserName,UserRelationshipName) values('Carol','James'); Query OK, 1 row affected (0.20 sec) mysql> insert into PairDemo(UserName,UserRelationshipName) values('Carol','David'); Query OK, 1 row affected (0.25 sec) mysql> insert into PairDemo(UserName,UserRelationshipName) values('Sam','David'); Query OK, 1 row affected (0.19 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from PairDemo;
Output
+--------+----------+----------------------+ | UserId | UserName | UserRelationshipName | +--------+----------+----------------------+ | 1 | John | James | | 2 | Carol | James | | 3 | Carol | David | | 4 | Sam | David | +--------+----------+----------------------+ 4 rows in set (0.00 sec)
The following is the query to apply CROSS JOIN −
mysql> SELECT U.UserName, UR.UserRelationshipName -> FROM ( -> (SELECT DISTINCT UserName from PairDemo) U -> CROSS JOIN -> (SELECT DISTINCT UserRelationshipName from PairDemo) UR -> ) WHERE NOT EXISTS ( -> SELECT * FROM PairDemo tbl -> WHERE tbl.UserName = U.UserName -> AND tbl.UserRelationshipName = UR.UserRelationshipName -> ) ;
Here is the output that displays the result of the above query implementing CROSS JOIN −
+----------+----------------------+ | UserName | UserRelationshipName | +----------+----------------------+ | Sam | James | | John | David | +----------+----------------------+ 2 rows in set (0.03 sec)
Advertisements