我在表加入时遇到问题。我已经在谷歌搜索但无法解决此问题。我想在连接表中获得最多4行。我正在把我的虚拟桌面结构放在这里。
here is table `users`
--------------------
| id | name |
--------------------
| 1 | John |
--------------------
| 2 | Mohn |
--------------------
here is table `user_transections`
------------------------------------------------
| id | user_id | amount | created_at |
------------------------------------------------
| 1 | 1 | 20 | xxxx-xx-xx xx:xx:xx |
------------------------------------------------
| 2 | 1 | 30 | xxxx-xx-xx xx:xx:xx |
------------------------------------------------
| 3 | 1 | 50 | xxxx-xx-xx xx:xx:xx |
------------------------------------------------
| 4 | 1 | 60 | xxxx-xx-xx xx:xx:xx |
------------------------------------------------
| 5 | 2 | 10 | xxxx-xx-xx xx:xx:xx |
------------------------------------------------
| 6 | 2 | 15 | xxxx-xx-xx xx:xx:xx |
------------------------------------------------
| 7 | 2 | 80 | xxxx-xx-xx xx:xx:xx |
------------------------------------------------
我想为每个用户的表匹配只加入3行
SELECT user.name,user_transections.amount FROM users
INNER JOIN user_transections on user.id = user_transections.user_id
//我如何在此处添加限制以加入最多三行横切表
答案 0 :(得分:2)
这是MySQL的痛苦。最通用的方法是使用变量:
select ut.*
from (select ut.*,
(@rn := if(@u = user_id, @rn + 1,
if(@u := user_id, 1, 1)
)
) as rn
from (select ut.*
from user_transections ut
order by user_id, created_at desc
) ut cross join
(select @u := -1, @rn := 0) params
) ut
where rn <= 3;
如果您只有两个用户(似乎不太可能),union all
更简单:
(select ut.*
from user_transactions ut
where user_id = 1
order by created_at desc
limit 3
) union all
(select ut.*
from user_transactions ut
where user_id = 2
order by created_at desc
limit 3
);
第三种方法使用相关子查询。这是一个版本:
select ut.*
from user_transactions ut
where ut.id >= coalesce( (select ut2.id
from user_transactions ut2
where ut2.user_id = ut.user_id
order by ut2.id desc
limit 1 offset 2
), ut.id
);
要获得此查询的效果,您需要user_transactions(user_id, id)
上的索引。