CROSS JOIN vs INNER JOIN in SQL

前端 未结 12 930
醉酒成梦
醉酒成梦 2020-11-22 03:16

What is the difference between CROSS JOIN and INNER JOIN?

CROSS JOIN:

SELECT 
    Movies.CustomerID, Movie         


        
12条回答
  •  [愿得一人]
    2020-11-22 03:41

    Here is the best example of Cross Join and Inner Join.

    Consider the following tables

    TABLE : Teacher

    x------------------------x
    | TchrId   | TeacherName | 
    x----------|-------------x
    |    T1    |    Mary     |
    |    T2    |    Jim      |
    x------------------------x
    

    TABLE : Student

    x--------------------------------------x
    |  StudId  |    TchrId   | StudentName | 
    x----------|-------------|-------------x            
    |    S1    |     T1      |    Vineeth  |
    |    S2    |     T1      |    Unni     |
    x--------------------------------------x
    

    1. INNER JOIN

    Inner join selects the rows that satisfies both the table.

    Consider we need to find the teachers who are class teachers and their corresponding students. In that condition, we need to apply JOIN or INNER JOIN and will

    enter image description here

    Query

    SELECT T.TchrId,T.TeacherName,S.StudentName 
    FROM #Teacher T
    INNER JOIN #Student S ON T.TchrId = S.TchrId
    
    • SQL FIDDLE

    Result

    x--------------------------------------x
    |  TchrId  | TeacherName | StudentName | 
    x----------|-------------|-------------x            
    |    T1    |     Mary    |    Vineeth  |
    |    T1    |     Mary    |    Unni     |
    x--------------------------------------x
    

    2. CROSS JOIN

    Cross join selects the all the rows from the first table and all the rows from second table and shows as Cartesian product ie, with all possibilities

    Consider we need to find all the teachers in the school and students irrespective of class teachers, we need to apply CROSS JOIN.

    enter image description here

    Query

    SELECT T.TchrId,T.TeacherName,S.StudentName 
    FROM #Teacher T
    CROSS JOIN #Student S 
    
    • SQL FIDDLE

    Result

    x--------------------------------------x
    |  TchrId  | TeacherName | StudentName | 
    x----------|-------------|-------------x            
    |    T2    |     Jim     |    Vineeth  |
    |    T2    |     Jim     |    Unni     |
    |    T1    |     Mary    |    Vineeth  |
    |    T1    |     Mary    |    Unni     |
    x--------------------------------------x
    

提交回复
热议问题