The difference and use of UNION ALL and UNION in SQL

  At work, you may encounter vertical merging of data from two tables, and the UNION and UNION ALL keywords will be used at this time.

  The difference is: UNION will sort and deduplicate the data, and the query efficiency is low.

        UNION ALL does not perform deduplication and sorting, and the query efficiency is high.

  It should be noted that two or more tables to be merged need to ensure that the number of their fields is the same, otherwise an error will be reported .

Such as: merging Student and Course tables

 

  SELECT Student ID, Name, Age, Course ID FROM Student

       UNION ALL 

       SELECT course number, course name, category, credits FROM Course;

  Note: If you are used to adding a semicolon at the end of SQL, don't add a semicolon after the first SELECT, just add it at the end. I have encountered such a low-level error at work.

Below are the query results. (Just for demonstration of course, this is a pointless merge because the fields and data are inconsistent)

  Sometimes the number of fields in the two tables is different , but if they must be merged, then add the missing fields by aliasing them , such as

    

  SELECT Student ID, Name, Age, Course ID, Null as Remarks   FROM Student

       UNION ALL 

       SELECT course number, course name, category, credits, remarks  FROM Course;

The result is as follows:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324856770&siteId=291194637