Analysis of mysql union and union all, analysis of mysqlunionall
In the database, the UNION and union all keywords combine the two results into one, but both have different usage and efficiency.
UNION in MySQL
UNION filters out duplicate records after table link. Therefore, after table link, it sorts the generated result sets and deletes duplicate records before returning results. In most applications, duplicate records are not generated. The most common is the UNION of Process Tables and historical tables. For example:
select * from gc_dfys union select * from ls_jg_dfys
This SQL statement extracts the results of two tables at run time, sorts and deletes duplicate records using the sorting space, and finally returns the result set. If the table has a large amount of data, it may cause disk sorting.
Union all in MySQL
Union all simply merges the two results and returns them. In this way, if duplicate data exists in the two returned result sets, the returned result sets will contain duplicate data.
In terms of efficiency, union all is much faster than UNION. Therefore, if you can confirm that the two results of the merge do not contain duplicate data, use union all, as shown below:
select * from gc_dfys union all select * from ls_jg_dfys
If Union is used, all returned rows are unique, as if you have used DISTINCT for the entire result set
If Union all is used, all rows are returned.
If you want to use the order by or LIMIT clause to classify or LIMIT all UNION results, parentheses should be added to a single SELECT statement, and put order by or LIMIT behind the last one:
(SELECT a FROM tbl_name WHERE a=10 AND B=1) UNION(SELECT a FROM tbl_name WHERE a=11 AND B=2)ORDER BY a LIMIT 10;
You can do this in a bit of trouble:
select userid from (select userid from testa union all select userid from testb) t order by userid limit 0,1;
If you still want to group by and have other conditions, then:
select userid from (select userid from testa union all select userid from testb) t group by userid having count(userid) = 2;
Note: there must be an alias behind the brackets of union. Otherwise, an error is reported.
Of course, if the data size of several tables in union is large, we recommend that you export the text in the pilot mode and execute it using scripts.
Because SQL is purely used, the efficiency will be relatively low, and it will write temporary files. If your disk space is not large enough, it may cause errors.
Error writing file '/tmp/MYLsivgK' (Errcode: 28)
Summary
The above is the mysql union and union all introduced by the small Editor. I hope it will be helpful to you. If you have any questions, please leave a message and the small editor will reply to you in time. Thank you very much for your support for the help House website!