MySQL 按关键字排序不适用于从两个 table 的内部连接插入 table

MySQL order by keyword not working with insert into table from the inner join of two tables

这就是我的 MySQL 查询,按关键字排序在这里不起作用。无法弄清楚它有什么问题。

insert into leaderboard 
select student.student_name as name , sum(marks) as total 
from marks inner join student on student.student_id = marks.student_id 
group by marks.student_id order by total desc;

leaderboard table output image

您当前的插入距离不远,但作为实践,您应该始终明确列出要插入的目标列,即使用此版本:

INSERT INTO leaderboard (name, total)   -- or whatever the column names are called
SELECT s.student_name, SUM(m.marks)
FROM marks m
INNER JOIN student s ON s.student_id = m.student_id
GROUP BY s.student_id;

关于您在 leaderboard table 中看到或不看到的顺序,感谢 SQL table 模仿 无序 组数据。也就是说,SQL table 中实际上没有任何内在顺序。如果您想按特定顺序查看数据,请在查询时(而不是在插入时)使用 ORDER BY 子句:

SELECT name, total
FROM leaderboard
ORDER BY total DESC;