简体   繁体   English

如何获取基于特定列的所有不同行?

[英]How to get all distinct rows based on a particular column?

It seems due to changes in MySQL 5.7 or higher, the SQL mode ONLY_FULL_GROUP_BY is enabled by default so the good old code I had which looked like the following: 似乎是由于MySQL 5.7或更高版本的更改,默认情况下启用了SQL模式ONLY_FULL_GROUP_BY,所以我的旧代码如下所示:

Table::where('name', 'LIKE', '%'.$search_str.'%')
    ->groupBy('name')
    ->get();

now throws the error... 现在抛出错误...

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column

I tried updating my code in various ways to try and make it work but no luck. 我尝试以各种方式更新代码以尝试使其正常运行,但是没有运气。

This is what I currently have: 这是我目前拥有的:

Table::where('name', 'LIKE', '%'.$search_str.'%')
    ->selectRaw('name, ANY_VALUE(id), ANY_VALUE(col_a), ANY_VALUE(col_b), ANY_VALUE(col_c), ANY_VALUE(col_d)')
    ->groupBy('name')
    ->get();

This doesn't throw any errors but the column data is missing. 这不会引发任何错误,但是缺少列数据。

I've also tried: 我也尝试过:

Table::where('name', 'LIKE', '%'.$search_str.'%')
    ->groupBy('name')
    ->groupBy('id')
    ->get();

Which does not return distinct rows based on 'name'. 不会根据“名称”返回不同的行。 It just returns everything. 它只是返回所有内容。

How can I do this in Laravel Eloquent or raw MySQL? 如何在Laravel Eloquent或原始MySQL中做到这一点?

The groupBy() method groups the collection's items by a given key. groupBy()方法通过给定键将集合的项目分组。 You should get a collection first: 您应该先获得一个收藏集:

Table::where('name', 'LIKE', '%'.$search_str.'%')
    ->get()
    ->groupBy('name');

In config/database.php file change 'strict' => true, to 'strict' => false, and try config/database.php文件中,将'strict' => true,更改为'strict' => false,然后尝试

Table::where('name', 'LIKE', '%'.$search_str.'%')
->groupBy('name')
->get();

I am not sure if you are looking for this. 我不确定您是否正在寻找这个。

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

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