【问题标题】:Join table only few row in MySQL platform [duplicate]在MySQL平台中加入表只有几行[重复]
【发布时间】:2018-09-25 06:47:57
【问题描述】:

我在加入表格时遇到问题。我已经在谷歌搜索但无法解决这个问题。我想在连接表中获得最多 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 // 如何在此处添加限制以加入最多三行横断面表

【问题讨论】:

  • 你将如何选择每个 id 的 3 条记录?按最大数量或随机或任何顺序?
  • @âńōŋŷXmoůŜ created_at 最新排名前三的订单
  • 请参阅下面的答案以及在此 SO 帖子顶部找到的已回答帖子。如果您有困难,请通过 jbacoy3ATyahooDotCom 告诉我。
  • 谢谢,@âńōŋŷXmoůŜ 会告诉你的

标签: mysql sql join greatest-n-per-group


【解决方案1】:

这对 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) 上的索引。

【讨论】:

  • 谢谢,亲爱的第三种方法对我有用,但是当我选择更多的一千个条目时,它需要大量的执行时间
  • 变量的使用效率更高,现在它对我有用 谢谢:D
猜你喜欢
  • 2023-03-06
  • 1970-01-01
  • 2013-05-24
  • 2016-03-06
  • 2023-03-24
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 2019-03-07
相关资源
最近更新 更多