简体   繁体   English

mysql 联合换单

[英]mysql union changing order

I'm having issues using the union clause.我在使用 union 子句时遇到问题。 Individually, the two queries run the way that I want them to.单独地,这两个查询按照我想要的方式运行。

  • The first query should be students with grades 8 or higher.第一个查询应该是 8 年级或更高年级的学生。 The data should be ordered by the grade DESC and if two students have the same grade, then it should be sorted by their name alphabetically.数据应按年级 DESC 排序,如果两个学生的年级相同,则应按姓名字母顺序排序。
  • The second query should be students with grade 7 or lower, the names should be null and their marks should be in ascending order第二个查询应该是7年级或以下的学生,名字应该是null,分数应该是升序排列

It's only when I put them together that the first query no longer has any order, the second query is fine.只有当我把它们放在一起时,第一个查询不再有任何顺序,第二个查询就可以了。 I made the second query, a nested query, to try to help but it didn't我做了第二个查询,一个嵌套查询,试图提供帮助,但它没有

(SELECT s1.name
        , g1.grade
        , s1.marks
FROM students s1
JOIN grades g1 ON s1.MARKS > g1.min_mark 
                 AND s1.MARKS < g1.max_mark
WHERE g1.grade > 7
ORDER BY grade DESC, name ASC)
UNION
(SELECT   s3.name
        , g2.grade
        , s2.marks
FROM students s2
LEFT JOIN grades g2 ON s2.MARKS > g2.min_mark 
                AND s2.MARKS < g2.max_mark
LEFT JOIN (SELECT * FROM students WHERE marks > 69) s3 ON s2.id = s3.id
WHERE g2.grade < 7
ORDER BY s2.marks)

Use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows.对单个 SELECT 语句使用 ORDER BY 并不意味着行在最终结果中出现的顺序,因为默认情况下 UNION 会生成一组无序的行。 1 1

It then gives this example of how to order the union result:然后给出了如何排序联合结果的示例:

(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;

In your query you probably want to remove the order by in the individual sub-queries and add this after:在您的查询中,您可能希望在各个子查询中删除order by并在之后添加:

ORDER BY grade DESC, name, marks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM