[英]Sort order of each select statement in a mysql union
I have some trouble with the sort order of my selects in my union statement.我在联合声明中选择的排序顺序有些问题。 I want to sort each select like firs for the name and second for the id.
我想对每个 select 进行排序,就像名称的第一名和 id 的第二名一样。
(SELECT
id,
name
FROM
table1
WHERE
active=1
ORDER BY name)
UNION
(SELECT
id,
name
FROM
table2
WHERE
active=1
ORDER BY id)
Everything work fine without the where clause, but this is necessary for my query.如果没有 where 子句,一切都可以正常工作,但这对于我的查询是必要的。 How can i do different sorts for each select?
我如何为每个 select 做不同的排序?
table1:表格1:
ID ![]() |
NAME![]() |
---|---|
1 ![]() |
First![]() |
3 ![]() |
Second![]() |
2 ![]() |
Third![]() |
table2:表2:
ID ![]() |
NAME![]() |
---|---|
1 ![]() |
First1![]() |
2 ![]() |
Second1![]() |
3 ![]() |
Third1![]() |
result table1+table2:结果表1+表2:
ID ![]() |
NAME![]() |
---|---|
1 ![]() |
First![]() |
3 ![]() |
Second![]() |
2 ![]() |
Third![]() |
1 ![]() |
First1![]() |
2 ![]() |
Second1![]() |
3 ![]() |
Third1![]() |
Try this:尝试这个:
Select id,name from
(
Select * from (
SELECT
t.id,
t.name,
@rownum := @rownum + 1 as row_number
FROM
test t
cross join (select @rownum := 0) r
WHERE
t.active=1
order by t.name ) tbl1
union all
select * from
(
SELECT
t.id,
t.name,
@rownum := @rownum + 1 as row_number
FROM
test2 t
cross join (select @rownum := 0) r
WHERE
t.active=1
order by t.id
) tbl2
) x order by row_number
you should use union all
你应该使用
union all
https://www.db-fiddle.com/f/dzBHKuzGmaQC8EmyuWcH2Y/2 https://www.db-fiddle.com/f/dzBHKuzGmaQC8EmyuWcH2Y/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.