簡體   English   中英

MySQL返回聯合選擇結果分組

[英]MySQL return union select results separated in groups

我想知道是否有可能從UNION中按其別名分組返回結果。 例如:

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

這樣的結果是:

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

實際上,我想要這樣的關聯數組:

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

我試過了,但是沒有用。 也許我做得不好。 可以通過單個查詢完成此操作,還是我必須做2個單獨的查詢。 謝謝。

您無法用union進行此操作,因為它會刪除重復項。 您可以與union all

一種方法是:

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

如果您不想在輸出中看到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