简体   繁体   English

Laravel-选择第一个出现列值的行

[英]Laravel - select rows with first occurance of column value

I have DB table urls similar to this 我有与此类似的数据库表urls

id | user_id | name
----------------------------
1  | 56      | John
2  | 25      | Carry
3  | 56      | Jim
4  | 12      | Jolana
5  | 12      | Ava 

What I need to do is to select the rows with the first occurance of user_id ordered in DESC by id . 我需要做的是选择在DESC中由id排序的user_id 首次出现的行。 In this case it would mean to select rows with IDs 5 , 3 and 2 . 在这种情况下这将意味着与ID来选择行532

Can this be achieved somehow using Eloquent, or if not, pure SQL? 是否可以使用Eloquent(如果不是,纯SQL)以某种方式实现? I can imagine writing a script for this but I would like to make it work with one query. 我可以想象为此编写脚本,但是我想使其与一个查询一起使用。

This is easy to do with SQL: 使用SQL很容易做到这一点:

select t.*
from t
where t.id = (select min(t2.id) from t t2 where t2.user_id = t.user_id);

You could use ROW_NUMBER : 您可以使用ROW_NUMBER

SELECT *
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY id DESC) AS rn
      FROM tab_name) sub
WHERE rn = 1
ORDER BY id DESC;

DBFiddle Demo - MariaDB 10.2 DBFiddle演示-MariaDB 10.2

DBFiddle Demo - MySQL 8.0 DBFiddle演示-MySQL 8.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM