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

相关推荐
AIgorithmGEEK3 小时前
MySQL 索引全解(下):建、查、删实战与知识速查表
数据库·mysql·b+树·索引
Lost_the_wind3 小时前
MySQL学习笔记四
mysql
唠点键盘之外的5 小时前
26 向量数据库实战:从 0 搭一条能用的检索链路(pgvector + Spring AI)
数据库·人工智能·spring
云和恩墨5 小时前
数据库监控简史:监控不止于告警——从图表大爆发到健康管理闭环
数据库
ly76896 小时前
MongoDB 事务开销实测:快照隔离下的写冲突、重试与分片事务边界
数据库·mongodb·事务·分片集群·快照隔离·写冲突
豆角焖肉6 小时前
Spring AOP 自定义注解实现系统操作日志
数据库·自定义注解·springaop·操作日志·aop 切面
金伟API10247 小时前
不会写复杂SQL怎么办?
数据库·sql
执笔为剑7 小时前
2.1.2-1、V8R3迁移到V8R6-Oracle兼容特性
数据库
geovindu8 小时前
sql:Search-Optimized SQL Queries using mysql 9.0
android·数据库·sql·mysql·数据库开发·数据库架构
for_ever_love__8 小时前
MySQL SELECT 与 WHERE 优化实战:可搜索条件、联合索引与执行计划
数据库·mysql·oracle·select·where·条件优化·查询优化技巧