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升序的情况下再排序

相关推荐
景煜拾年41 分钟前
InnoAI SQL 助手
运维·数据库·笔记·sql
.痞老板.1 小时前
mysql初阶--数据类型
android·数据库·mysql
Risehuxyc2 小时前
MySQL密码插件
数据库·mysql
腾科IT教育2 小时前
Oracle考试全解析:OCP、OCM认证体系与核心考点备考指南
数据库·oracle·开闭原则
叼烟扛炮12 小时前
Linux 学习笔记(五十六):IO 多路复用初探——select 的“三宗罪”
linux·服务器·数据库·笔记·学习·php
.痞老板.14 小时前
mysql初阶--数据库基础
数据库·mysql
城北徐宫16 小时前
MySQL约束条件一览
数据库·mysql
码农小河6616 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql
ClouGence18 小时前
数据库变更审批困局,被这个开源工具解决了
数据库·开源
TDengine (老段)18 小时前
TDengine IDMP 十大实用功能(9)
大数据·数据库·人工智能·物联网·时序数据库·tdengine·idmp