【问题标题】:How to convert SQL query to PHP and use AND operator in WHERE clause如何将 SQL 查询转换为 PHP 并在 WHERE 子句中使用 AND 运算符
【发布时间】:2018-06-19 02:29:38
【问题描述】:

我有下面的 php 查询,我想计算id 在列中存在的次数

$empCount = DB::table('m_employee')->count('group_id')->where('group_id',$idHolder);

价值观

//tblname is m_employee; column name is group_id and my search variable is $idHolder

错误信息是:

{"message":"调用成员函数 where() on integer",.......

对于这个例子,当我的$idHolder的值为1时,$empCount的结果应该是13,如果是2,结果是3。 在那之后,我如何在这个查询中使用AND 运算符:

DB::table('emp')->where('key',  $emp)->update([
   'id' => $id,
]);

where('key', $emp) AND ('monthyear', '06/2018'),基于上面cost_date 列中的日期(仅提取月份和年份)。我很难确定在哪里插入它。

【问题讨论】:

  • @user3783243 已更新。抱歉没有解释清楚,我所指的id 是指我的code 用于特定组名。
  • 您能否提供一些示例数据以及输出应该是什么?
  • @user3783243 请查看更新。谢谢。
  • 您应该使用group bycount 的每个id。不过,我不熟悉 larvel 是如何做到的。在常规 SQL 中,它是 select count(*), group_id from table where cost_date = ? group by group_id(...假设我正在正确阅读您想要的内容)
  • @downvoter 介意指出我需要改进的地方吗?

标签: php mysql laravel operators


【解决方案1】:

您可以简单地使用下面的查询进行计数

$empCount = DB::table('m_employee')->where('group_id',$idHolder)->count();

对于AND 运算符,您可以简单地链接 where 子句来模拟这个

DB::table('emp')->where('key', $emp)->where(DB::raw("(DATE_FORMAT(cost_date,'%m-%Y'))"), '=', '06-2018')->update([ 'id' => $id, ]);

【讨论】:

  • 感谢您解决计数问题。我可以提取与给定月份和年份匹配的日期吗?请参阅我上面的示例表。因此,如果我的日期是 06/2018,它应该与 2018-06-18 列匹配。谢谢,
  • 更新了我上面的答案,你可以试试。
  • MMM,说unxpected ',' 我尝试这样做时出错:DB::table('emp')->whereRaw("(DATE_FORMAT(monthyear,'%m/%Y'))"), '=', '06/2018')->update([ 'id' => $id, ]); 谢谢。
  • 我认为这不是问题,因为它在我的其他查询中运行良好。所以我试试,->whereRaw("(DATE_FORMAT(cost_date,'%m-%Y'))=",'06/2018')...,错误是Syntax error or access violation: 1064 You have an error in your SQL syntax;....
  • 干得好!我将在上面更新我的答案作为其他人的参考:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多