[英]Order by on one query of union in mysql
I have a query like this 我有这样的查询
SELECT t.id,t.name,t.count
FROM Teacher
UNION
SELECT '','',(SELECT count(*) FROM student)
Now I want to use order by only on the first query before union like this 现在我只想在联合之前的第一个查询上使用order
SELECT t.id,t.name,t.count
FROM Teacher
ORDER BY t.name ASC
UNION
SELECT '','', (SELECT count(*) FROM student)
but it does not work 但它不起作用
I have also used 我也用过
SELECT *
FROM (SELECT t.id,t.name,t.count FROM Teacher) as teacher
UNION
SELECT '','',(SELECT count(*) FROM student)
ORDER BY name ASC
but it includes the second query also in the order by and it changes its position also and I don't want order by on the second query only on the first. 但它也按顺序包含第二个查询,并且它也改变了位置,我不希望仅在第一个查询上对第二个查询进行排序。
You cannot order "parts" of a UNION; 您不能订购UNION的“零件”; even if you try to force it with subqueries, MySQL will just disregard it. 即使您尝试通过子查询强制使用它,MySQL也会忽略它。 You can create an extra ordering field though. 但是,您可以创建一个额外的订购字段。 here is a generic template for this method: 这是此方法的通用模板:
SELECT u.A, u.B, u.C
FROM
(
SELECT 0 as seq, A, B, C
FROM table1
UNION
SELECT 1 AS seq, A, B, C
FROM table2
) AS u
ORDER BY u.seq
No, you can't you need subquery
: 不,您不需要subquery
:
SELECT *
FROM (SELECT id, name, count
FROM Teacher
UNION
SELECT '', '', (SELECT count(*) FROM student)
) t
ORDER BY name;
Instead, i would rewrite as with single SELECT
statement : 相反,我将用单个SELECT
语句重写:
SELECT *
FROM (SELECT id, name, count
FROM Teacher
UNION
SELECT '', '', count(*)
FROM student
) t
ORDER BY name;
尝试使用(),它将使您仅在第一次查询时就订购
(SELECT t.id,t.name,t.count FROM Teacher ORDER BY t.name ASC) UNION (SELECT '','', (SELECT count(*) FROM student))
You need write a subquery and make seqnum
mark first query and second query then use multiple order by
on seqnum
and name
您需要编写一个子查询并使seqnum
标记为第一个查询和第二个查询,然后对seqnum
和name
使用多个order by
SELECT t.*
FROM (
SELECT 1 seqnum,t.id,t.name,t.count
FROM Teacher
UNION
SELECT 2,'','', (SELECT count(*) FROM student)
) t
ORDER BY t.seqnum,t.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.