MySQL高阶2159-分别排序两列

题目

编写解决方案,使:

  • first_col 按照升序排列。
  • second_col 按照 降序排列。

准备数据

python 复制代码
Create table If Not Exists Data (first_col int, second_col int)
    Truncate table Data
    insert into Data (first_col, second_col) values ('4', '2')
    insert into Data (first_col, second_col) values ('2', '3')
    insert into Data (first_col, second_col) values ('3', '1')
    insert into Data (first_col, second_col) values ('1', '4');

分析数据

a表

sql 复制代码
select row_number() over(order by first_col) as id, first_col
     from Data

b表

sql 复制代码
select row_number() over(order by second_col desc) as id, second_col
     from Data

根据关联条件将两表关联起来

sql 复制代码
select a.first_col, b.second_col
from
    (select row_number() over(order by first_col) as id, first_col
     from Data) a join
    (select row_number() over(order by second_col desc) as id, second_col
     from Data) b on a.id = b.id;

总结

如果两个表关联条件字段相同,也可以使用using(关联的字段名)

比如这道题,最后可以使用"using(id) " 代替 " on a.id = b.id"


本题错误做法

sql 复制代码
select * from data
    order by first_col asc,second_col desc;

因为本题是单独让每列排序,而上面做法second_col的降序会在first_col升序的情况下再排序

相关推荐
格调UI成品18 分钟前
DCS+PLC协同优化:基于MQTT的分布式控制系统能效提升案例
数据库·云边协同
牵牛老人1 小时前
Qt C++ 复杂界面处理:巧用覆盖层突破复杂界面处理难题之一
数据库·c++·qt
a_blue_ice1 小时前
JAVA 面试 MySQL
java·mysql·面试
GBASE1 小时前
GBASE南大通用技术分享:构建最优数据平台,GBase 8s数据库安装准备(三)
数据库
言之。2 小时前
Django REST Framework 中 @action 装饰器详解
数据库·sqlite
十八旬3 小时前
苍穹外卖项目实战(day7-1)-缓存菜品和缓存套餐功能-记录实战教程、问题的解决方法以及完整代码
java·数据库·spring boot·redis·缓存·spring cache
Java水解4 小时前
【MySQL】数据库基础
后端·mysql
沃夫上校4 小时前
MySQL 中文拼音排序问题
java·mysql
要一起看日出4 小时前
MVCC-多版本并发控制
数据库·mysql·mvcc
Hx__4 小时前
MySQL InnoDB 的 MVCC 机制
数据库·mysql