我想知道是否可以从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]
]我试过了,但不起作用。也许我做得不好。这可以用一个查询来完成吗,或者我必须做两个独立的查询。谢谢。
发布于 2017-01-18 21:17:51
您不能使用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;https://stackoverflow.com/questions/41720461
复制相似问题