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

相关推荐
Chasing__Dreams1 小时前
kafka--基础知识点--6.4--LSO
数据库·分布式·kafka
极限实验室8 小时前
APM(一):Skywalking 与 Easyearch 集成
数据库·云原生
饕餮争锋8 小时前
SQL条件中WHERE 1=1 的功能
数据库·sql
玄斎8 小时前
MySQL 单表操作通关指南:建库 / 建表 / 插入 / 增删改查
运维·服务器·数据库·学习·程序人生·mysql·oracle
编织幻境的妖9 小时前
SQL查询连续登录用户方法详解
java·数据库·sql
编程小Y9 小时前
MySQL 与 MCP 集成全解析(核心原理 + 实战步骤 + 应用场景)
数据库·mysql·adb
零度@10 小时前
SQL 调优全解:从 20 秒到 200 ms 的 6 步实战笔记(附脚本)
数据库·笔记·sql
Miss_Chenzr10 小时前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
lvbinemail10 小时前
Grafana模板自动复制图表
数据库·mysql·zabbix·grafana·监控
Miss_Chenzr10 小时前
Springboot旅游景区管理系统9fu3n(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·旅游