mysql - 选择一列 + 另一列,最大日期
问题描述
我有这张桌子。我需要选择registration = 1 的一行,然后选择session = 1 和last created_at 的一行。
2 行 - 注册和最后一次会议
我尝试了row_number,但它在mysql中不起作用。(?)
如何编写连接查询?
期望它 在此处输入图像描述
first row: registration = 1 - user_id = 1
second row: session = 1 - user_id = 1 - created_at = max(created_at) where user_id = 1
解决方案
例如,这是一个具有相关子查询的联合,以获取最后一个会话
drop table if exists u,m,memos,um;
create table u (id int auto_increment primary key,uID int, reg int, sess int,dt date);
insert into u (uid,reg,sess,dt) values
( 1 , 1,0,'2018-01-01') ,
( 1 , 0,1,'2018-01-01'),
( 1 , 0,1,'2018-02-01');
select u.* from u where reg = 1
union
select u.* from u where sess = 1 and id = (select max(id) from u u1 where u1.uid = u.uid)
order by uid,id;
+----+------+------+------+------------+
| id | uID | reg | sess | dt |
+----+------+------+------+------------+
| 1 | 1 | 1 | 0 | 2018-01-01 |
| 3 | 1 | 0 | 1 | 2018-02-01 |
+----+------+------+------+------------+
推荐阅读
- sql-server - SQL Server 连接读取超时
- swiftui - SwiftUI:使用计时器更新模型并将其反映在 UI 中
- python - Pygame 窗口仅在“无响应”时响应
- arrays - 如何从 iOS Swift 中的 json 获取价值?
- python - 计算 Pandas 列中值的 3 个月滚动计数
- apache - 访问 URL 的用户会两次附加上下文路径
- java - 需要帮忙。此代码删除除索引 0 以外的所有内容
- neo4j - 遍历对象列表并通过对象 Neo4j 的属性创建节点
- php - 在一个 td 中附加相似的日期记录
- vue.js - Vue3 Composition:运行时的动态默认元素类