我有这样的查询
SELECT t.id,t.name,t.count
FROM Teacher
UNION
SELECT '','',(SELECT count(*) FROM student)
现在我只想在联合之前的第一个查询上使用order by
SELECT t.id,t.name,t.count
FROM Teacher
ORDER BY t.name ASC
UNION
SELECT '','', (SELECT count(*) FROM student)
但不起作用
我也用过
SELECT *
FROM (SELECT t.id,t.name,t.count FROM Teacher) as teacher
UNION
SELECT '','',(SELECT count(*) FROM student)
ORDER BY name ASC
但是它也按顺序包含第二个查询,并且它也改变了位置,我不希望仅在第一个查询上对第二个查询进行排序。
答案 0 :(得分:2)
您不能订购UNION的“零件”;即使您尝试通过子查询强制使用它,MySQL也会忽略它。但是,您可以创建一个额外的订购字段。 这是此方法的通用模板:
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
答案 1 :(得分:1)
不,您不需要subquery
:
SELECT *
FROM (SELECT id, name, count
FROM Teacher
UNION
SELECT '', '', (SELECT count(*) FROM student)
) t
ORDER BY name;
相反,我会像使用单个SELECT
语句那样重写:
SELECT *
FROM (SELECT id, name, count
FROM Teacher
UNION
SELECT '', '', count(*)
FROM student
) t
ORDER BY name;
答案 2 :(得分:1)
尝试使用(),它将使您仅在第一次查询时就订购
(SELECT t.id,t.name,t.count FROM Teacher ORDER BY t.name ASC) UNION (SELECT '','', (SELECT count(*) FROM student))
答案 3 :(得分:0)
您需要编写一个子查询,并在第一个查询和第二个查询上标记seqnum
,然后在order by
和seqnum
上使用多个name
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