首页 > 解决方案 > 选择一列 + 另一列,最大日期

问题描述

我有这张桌子。我需要选择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

标签: mysql

解决方案


例如,这是一个具有相关子查询的联合,以获取最后一个会话

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 |
+----+------+------+------+------------+

推荐阅读