如何选择最新的每一个option_id的user_id?
+-----+-----------+---------+-------+
| id | option_id | user_id | value |
+-----+-----------+---------+-------+
| 241 | 6 | 2 | 2 |
| 240 | 5 | 2 | 1 |
| 90 | 5 | 2 | 15 |
| 75 | 4 | 2 | 11 |
| 76 | 4 | 2 | 1 |
| 77 | 4 | 2 | 2 |
| 72 | 4 | 1 | 10 |
| 71 | 4 | 1 | 15 |
| 70 | 5 | 1 | 2 |
+-----+-----------+---------+-------+如何使用雄辩的语言编写查询,只实现给定option_id的每个user_id中的最新一个?
对于提供的表,user_id 2的输出应该是记录id: 241,240,75。
user_id 1记录: 72,70
编辑:
为了重新迭代,我想返回一个给定的option_id的最新user_id集合。
因此,对于user_id 2,将有3条记录:
对于user_id 1,只有2条记录:
发布于 2019-04-11 16:34:19
事实证明,这就像:
$options= DB::table('options')
->where('user_id', Auth::getUser()->id)
->groupBy("option_id")
->orderBy("option_id", "DESC")
->get();但必须将此查询的严格模式设置为false,并在检索到数据后将其恢复为true。
在查询之前:
// turn off strict mode for the below query
config()->set('database.connections.mysql.strict', false);
\DB::reconnect(); //important as the existing connection if any would be in strict mode在查询之后:
//now changing back the strict ON
config()->set('database.connections.mysql.strict', true);
\DB::reconnect();发布于 2019-04-09 15:13:32
假设表是用户,并考虑到$id是动态的。也许这个你的意思是:
$user = User::where('user_id', $id)
->orderBy('id', 'DESC')
->get();最后,使用此代码$user->unique('option_id')来获得实际结果。
希望它有帮助:)
发布于 2019-04-09 18:04:04
如果您的表名为user_options,下面是一个雄辩的查询,用于选择您要查找的记录。
$getValues = DB::table('user_options')
->join(DB::raw('(SELECT max(user_options.id) FROM user_options INNER JOIN (
SELECT option_id, user_id FROM user_options GROUP BY option_id, user_id) sets
WHERE user_options.option_id = sets.option_id AND user_options.user_id = sets.user_id
GROUP BY user_options.option_id, user_options.user_id
) valuerecords'),
function($join)
{
$join->on('user_options.id', '=', 'valuerecords.id');
})->select(
'id',
'option_id',
'user_id',
'value'
)->get();原始select查询获取最新记录的is,然后将其连接回表以获取记录。
请注意,“最新”记录是具有最高id的记录,因此它将获取记录77而不是75。如果以不同的方式定义最新的查询,则可以相应地更改原始查询。
https://stackoverflow.com/questions/55595707
复制相似问题