📜  SQL cross-join(1)

📅  最后修改于: 2023-12-03 14:47:34.799000             🧑  作者: Mango

SQL Cross-Join

What is a Cross-Join?

A cross-join, also known as a Cartesian product, is a join operation in SQL that combines each row from one table with each row from another table. It does not match any rows like other join types.

Syntax

The syntax for a cross-join is as follows:

SELECT <column_list>
FROM <table1>
CROSS JOIN <table2>
Example

For example, consider two tables: "students" and "grades". The "students" table has columns "Student ID" and "Name", while the "grades" table has columns "Student ID" and "Grade".

Assuming the following data:

students table
+------------+--------+
| Student ID |  Name  |
+------------+--------+
|     1      |  John  |
|     2      |  Jane  |
+------------+--------+

grades table
+------------+-------+
| Student ID | Grade |
+------------+-------+
|     1      |   A   |
|     2      |   B   |
+------------+-------+

The following cross-join SQL query:

SELECT s.Name, g.Grade
FROM students s
CROSS JOIN grades g

would return:

+--------+-------+
|  Name  | Grade |
+--------+-------+
|  John  |   A   |
|  Jane  |   A   |
|  John  |   B   |
|  Jane  |   B   |
+--------+-------+
Conclusion

A cross-join is useful when there is a need to combine data from two tables without a common field to join on. However, due to its performance implications, a cross-join should be used judiciously and mostly as a last resort.