【问题标题】:Laravel "group by having" query issuesLaravel“按拥有分组”查询问题
【发布时间】:2015-01-01 02:04:42
【问题描述】:

请我尝试在原始 sql 中运行类似这样的查询

SELECT COUNT(cntr) count, address,
description FROM resti GROUP BY cntr = HAVING count > 1

在 laravel 中。

我试过了

 DB::table("resti")
                 ->select(DB::raw("COUNT(cntr) count, address, description"))
                 ->groupBy("cntr")
                 ->havingRaw("count > 1")
                 ->get();

但它给出了一些聚合错误。

【问题讨论】:

  • 尝试toSql()查看最终查询。
  • 谢谢。它实际上输出了正确的sql。不确定问题可能来自哪里。不过非常感谢。
  • 你有什么错误信息?具体在哪里?
  • 我在删除 get() 后在查询构建器的末尾添加了一个计数,即我添加了 ->count() 并将 select count(*) 打印为来自 resti 的聚合按 cntr 分组,计数 > 1 会引发未知列错误。
  • 当然,count > 1 是未知列。

标签: php mysql laravel eloquent


【解决方案1】:

你的 SQL 查询应该是这样的

SELECT COUNT(cntr) count, address, description 
FROM resti 
GROUP BY cntr  
HAVING COUNT(cntr) > 1

在 Laravel 中你的代码应该是这样的

DB::table("resti")
->select(DB::raw("COUNT(cntr) count, address, description"))
->groupBy("cntr")
->havingRaw("COUNT(cntr) > 1")
->get();

【讨论】:

  • 查询添加了与“haveRaw”条件不匹配的值,你能帮忙吗?
  • @always-a-learner 你能解释更多,代码示例或更多细节!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 2011-09-08
  • 2017-04-22
  • 2017-07-09
  • 1970-01-01
相关资源
最近更新 更多