【问题标题】:How to find product by manufacturer?如何按制造商查找产品?
【发布时间】:2022-12-01 00:01:26
【问题描述】:

我正在使用 Laravel 8 并使用原始查询。我已添加查询以按制造商获取产品数量,但面临以下错误。

SQLSTATE[42000]: Syntax error or access violation: 1055 'ngtonlin_superadmin.m.manufacturerid'
isn't in GROUP BY (SQL: select `m`.`manufacturerid` as `id`, `m`.`name`, `m`.`logowidth`,
`m`.`logoheight`, count(p.id) as total from `products` as `p` inner join `manufacturer` as `m` on
`m`.`manufacturerid` = `p`.`manufacturer_id` group by `p`.`manufacturer_id` order by `total` desc limit 5)

我的查询是

DB::table('products as p')
        ->select('m.manufacturerid as id','m.name','m.logowidth','m.logoheight', DB::raw('count(p.id) as total'))
        ->join('manufacturer as m','m.manufacturerid','=','p.manufacturer_id')
        ->groupBy('p.manufacturer_id')
        ->orderBy('total', 'DESC')
        ->limit(5)
        ->get();

【问题讨论】:

  • 您还需要在 groupBy 中包含您选择的所有非聚合列。在你的情况下是m.name, m.logowidth, m.logoheight
  • 你能告诉我我添加了哪一列吗?
  • 您需要添加 SELECT 中未聚合的所有列(被 AVG()、MIN()、MAX() 等包围)。
  • 谢谢,这对我不好。

标签: mysql laravel


【解决方案1】:

我认为你需要使用

->groupBy(m.manufacturerid, 'm.name','m.logowidth','m.logoheight')

不是

->groupBy('p.manufacturer_id')

因为,我认为 p.manufacturer_id = m.manufacturerid,而你在选择部分使用了 m.manufacturerid。

【讨论】:

    【解决方案2】:

    尝试这个: DB::table('products as p')->join('manufacturer as m','m.manufacturerid','p.manufacturer_id')->selectRaw('m.manufacturerid as id')->selectRaw(' m.name')->selectRaw('m.logowidth')->selectRaw('m.logoheight')->selectRaw('count(p.id) as total')->groupBy('p.manufacturer_id') ->orderBy('total', 'DESC')->limit(5)->get();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多