php - Laravel 选择查询
问题描述
我为以下选择语句构建查询
SELECT empname, COUNT(empstatus)
FROM empattens
WHERE empstatus='Present'
AND id=1;
我使用的代码如下
Empatten::where('id', $id)
->where('empstatus', '=', 'Present')
->get()
->count('empstatus');
我只收到count(empstatus)
,但我empname
也需要,
解决方案
您可以使用该select()
方法指定要选择的字段,然后将其与DB::raw()
选择您的COUNT()
.
Empatten::select('empname', \DB::raw("COUNT(*) AS count"))
->where('id', $id)
->where('empstatus', '=', 'Present')
->get();
但这不一定是有效的 SQL,因为您在选择列时使用聚合函数(在本例中COUNT()
为 ,但其他示例为MIN()
、MAX()
、 )。您应该为选择列表中不属于聚合语句的列AVG()
指定 a 。GROUP BY
我们可以通过使用该groupBy()
方法来做到这一点 - 结果不应该改变,因为您正在寻找一个特定的 ID。
Empatten::select('empname', \DB::raw("COUNT(*) AS count"))
->where('id', $id)
->where('empstatus', '=', 'Present')
->groupBy('empname')
->get();
推荐阅读
- java - 自动舍入 SQL d
- python-3.x - 使用 Python peewee 连接到 MySQL 时如何指定 tls 版本“TLSv1.2”
- python - Django ForeignKey 仅删除“子”元素
- selenium - WebDriverException: unknown error: Chrome failed to start: exited exceptionly error running Selenium Grid on Server using ChromeDriver and Chrome
- ms-access - MS Access 365 - 创建包含链接文件的子表单
- css - 为什么我的 Gatsby/Material-UI 站点呈现的比视口略大?
- azure - 在 azure ml 管道中,使用大型数据集训练模型时出错
- bash - 如何检查 bash 脚本的参数是否为“标志”
- ios - Ionic:不再接受 iOS UIWebView
- c# - 有谁知道为什么 C# 语音识别突然不再起作用了?