简体   繁体   English

MySQL返回联合选择结果分组

[英]MySQL return union select results separated in groups

I would like to know if is possible to return the results from UNION grouped by their alias. 我想知道是否有可能从UNION中按其别名分组返回结果。 For instance: 例如:

(SELECT * FROM table1) AS first
UNION
(SELECT * FROM table2) AS second

so that the result is: 这样的结果是:

first = contains all table1 rows
second = contains all table2 rows

Practically i want an associative array like this: 实际上,我想要这样的关联数组:

[]=>[
    'first'=>[table1 results],
    'second'=>[table2 results]
]

I tried it but doesn't work. 我试过了,但是没有用。 Maybe i'm doing it bad. 也许我做得不好。 Can this be done with a single query or i've to do 2 separated queries. 可以通过单个查询完成此操作,还是我必须做2个单独的查询。 Thanks. 谢谢。

You cannot do this with union because it removes duplicates. 您无法用union进行此操作,因为它会删除重复项。 You can with union all . 您可以与union all

One way is: 一种方法是:

SELECT t.*, 0 as which FROM table1 t
UNION ALL
SELECT t.*, 1 FROM table2 t
ORDER BY which;

If you don't want to see which in the output, use a subquery: 如果您不想在输出中看到which ,请使用子查询:

select . . .
from (select t.*, 0 as which from table1 t union all
      select t.*, 1 as which from table1 t
     ) t
order by which;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM