tp6 union and unionAll use

Precondition: Each union method is equivalent to an independent SELECT statement.

The SELECT statements inside the UNION must have the same number of columns. Columns must also have similar data types. Also, the order of the columns in each SELECT statement must be the same.

Therefore, the table structure must be the same

union all is to connect the two connected query result tables;
union is to connect the two connected query result tables and perform deduplication processing;

The difference between union and union all is
that union needs to scan duplicate values ​​for deduplication processing, so the efficiency is low. If the merge does not deliberately delete duplicate rows, it is recommended to use Union All

eg1:
$a = Db('edu_testtable_one')->field('name')
    ->table('edu_testtable_one')
    ->union('SELECT name from edu_testtable_two')
    ->union('SELECT  name from  edu_testtable_three')
    ->select();

eg2:
$a = Db('edu_testtable_one')->field('name')
    ->table('edu_testtable_one')
    ->union(['SELECT name from edu_testtable_two', 'SELECT  name from  edu_testtable_three'])
    ->select();

eg1 is equivalent to eg2. The query results are as follows:

 

 eg3:

$a = Db('edu_testtable_one')->field('name') ->table('edu_testtable_one') ->unionAll('SELECT name from edu_testtable_two') ->unionAll('SELECT name from edu_testtable_three') ->select();

eg4:

$a = Db('edu_testtable_one')->field('name') ->table('edu_testtable_one') ->union(['SELECT name from edu_testtable_two', 'SELECT name from edu_testtable_three'], true) ->select();

eg3 is equivalent to eg4. The query results are as follows:

 

 

Guess you like

Origin blog.csdn.net/qq_58778333/article/details/130147190