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

相关推荐
NocoBase1 小时前
【2.0 教程】第 1 章:认识 NocoBase ,5 分钟跑起来
数据库·人工智能·开源·github·无代码
Hoshino.412 小时前
基于Linux中的数据库操作——下载与安装(1)
linux·运维·数据库
Oueii4 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
未来龙皇小蓝4 小时前
【MySQL-索引调优】11:Group by相关概念
数据库·mysql·性能优化
2401_831824964 小时前
使用Fabric自动化你的部署流程
jvm·数据库·python
njidf5 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
twc8295 小时前
大模型生成 QA Pairs 提升 RAG 应用测试效率的实践
服务器·数据库·人工智能·windows·rag·大模型测试
@我漫长的孤独流浪5 小时前
Python编程核心知识点速览
开发语言·数据库·python
2401_851272995 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
枕布响丸辣5 小时前
MySQL 从入门到精通:完整操作手册与实战指南
数据库·mysql