我有这张桌子。我需要选择注册= 1的一行,然后选择会话= 1并最后一次created_at的一行。
2行-注册和最后一个会话
我尝试了row_number,但是在mysql中不起作用。 (?)
如何编写联接查询?
预期 enter image description here
first row: registration = 1 - user_id = 1
second row: session = 1 - user_id = 1 - created_at = max(created_at) where user_id = 1
答案 0 :(得分:0)
这是具有相关子查询的并集,以获取最后一个会话 例如
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 |
+----+------+------+------+------------+