我在数据库中多次使用相同的电子邮件ID,我需要获取并显示所有用户,不包括重复项。
请帮我解决这个问题
预期输出:
[
{
"donation_id": "DMS1900001",
"donor_name": "Naveen",
"phone": "9164020904",
"email": "naveen@vibhaa.in"
},
{
"donation_id": "DMS1900032",
"donor_name": "Naveen",
"phone": "9164020904",
"email": "abhilash@vibhaa.in"
}
]
我的代码:
$donordata = DB::table('donors')
->groupBy('email')
->get();
return $donordata;
和回应
SQLSTATE[42000]: Syntax error or access violation: 1055 'minidms_db.donors.id' isn't in GROUP BY (SQL:
select * from `donors` group by `email`)
但数据在表中:
[
{
"donation_id": "DMS1900001",
"donor_name": "Naveen",
"phone": "9164020904",
"email": "naveen@vibhaa.in",
},
{
"donation_id": "DMS1900002",
"donor_name": "Naveen",
"phone": "9164020904",
"email": "naveen@vibhaa.in",
},
{
"donation_id": "DMS1900035",
"donor_name": "Naveen",
"phone": "9164020904",
"email": "abhilash@vibhaa.in",
}
]
我只想在这里做一个不同的选择:
$donordata = DB::table('donors')
->distinct()
->get();
正如错误消息所述,这里的问题是您正在执行SELECT *
但仅按单个列分组:
select * from `donors` group by `email`
如果要使用GROUP BY
方法来删除重复项,则可以使用:
SELECT donation_id, donor_name, phone, email
FROM donors
GROUP BY donation_id, donor_name, phone, email;
但是,在这种情况下,仅调用 Larawel 的distinct()
函数会更容易一些。
编辑应用程序的数据库配置文件config/database.php
将 mysql 上的严格值更新为false
return [
'connections' => [
'mysql' => [
'strict' => false
]
]
]