【问题标题】:Get all the row using where min/max laravel使用 where min/max laravel 获取所有行
【发布时间】:2021-11-22 09:08:18
【问题描述】:

我正在尝试获取 all 我在“温度”中具有最小值但使用 min() 或 max() 仅返回最小值或最大值的行

目前我必须在最小值和“acktime”之前找到我想一次性获得所有行,但是:

$tmp = rawData::whereDate('acktime','=', $thisDay)->min('temperature');

这样我只得到最小值

$tmp = rawData::whereDate('acktime','=', $thisDay)->get()->min('temperature');

这样我只得到最小值

 $tmp = rawData::whereDate('acktime','=', $thisDay)->get('acktime')->min('temperature');

这样我得到null

$tmp = rawData::with('acktime','temperature')->whereDate('acktime','=', $thisDay)->min('temperature')->get();

这样我得到错误调用一个成员函数 get() on float

【问题讨论】:

  • 我认为没有比使用 2 个循环更好的方法了:1 查找 min 值和 1 查找包含 min 值的所有记录
  • 同时想要最小值和行有点矛盾,因为最小值是所有行的聚合。

标签: laravel


【解决方案1】:

你可以试试这个:

$tmp = rawData::whereDate('acktime','=', $thisDay)->orderBy('temperature', 'asc')->first();

【讨论】:

  • 嗯……你真是个天才!
  • 很高兴它对你有用。
【解决方案2】:

您可以构建自己的选择语句。 Using DB::raw 做最小操作。这将返回一行,包含预期的最小数据和acktime

$data = rawData::with('acktime','temperature')
    ->whereDate('acktime','=', $thisDay)
    ->select('acktime', DB::raw('min(temperature) as temperature'))
    ->first();

【讨论】:

  • 是的,这就是我现在正在做的事情,但是以不同的方式,我的代码出现了这个错误:Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select acktime, min(temperature) as temperature from raw_data` where date(acktime) = 2021-11 -01 限制 1) `你知道为什么吗?
  • 由于错误状态,您必须进行分组才能使其正常工作。正如我对你试图做的问题的评论中所说的那样,这是相互对抗的。您可以按 acktime 对数据进行分组吗?或类似您的查询将有多行,它可以按哪一列分组?
猜你喜欢
  • 2012-10-28
  • 2019-06-25
  • 2021-10-18
  • 2018-01-15
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 2020-08-22
相关资源
最近更新 更多