php 使用Laravel 10运行SQL原始查询

ix0qys7i  于 2023-06-28  发布在  PHP
关注(0)|答案(2)|浏览(154)

我有一个小查询要在我的控制器中运行,它在MySQL Workbench中运行得很好

SELECT
  subprocess_id,
  MAX(CASE WHEN step_no = '1' THEN s_name END) AS first_step,
  MAX(CASE WHEN step_no = '2' THEN s_name END) AS second_step,
  MAX(CASE WHEN step_no = '3' THEN s_name END) AS thrid_step,
  MAX(CASE WHEN step_no = '4' THEN s_name END) AS fourth_step,
  MAX(CASE WHEN step_no = '5' THEN s_name END) AS fifth_step,
  MAX(CASE WHEN step_no = '6' THEN s_name END) AS sixth_step
FROM
  worksteps
  where subprocess_id=8010
GROUP BY
  subprocess_id;

试图把它翻译成Laravel但没有成功

DB::table("worksteps")
->select("subprocess_id", "max (case when step_no = '1' then s_name end) as `first_step`", "max (case when step_no = '2' then s_name end) as `second_step`", "max (case when step_no = '3' then s_name end) as `thrid_step`", "max (case when step_no = '4' then s_name end) as `fourth_step`", "max (case when step_no = '5' then s_name end) as `fifth_step`", "max (case when step_no = '6' then s_name end) as `sixth_step`")
->where("subprocess_id", "=", 8010)
->groupBy("subprocess_id")
->get();

获取错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'max...

我没有max列,我在查询中使用了MAX(),以避免在一个主ID有两个相同的步骤ID的情况下出错。
如何在我的控制器显示功能中执行此操作?

egmofgnx

egmofgnx1#

尝试:

DB::table("worksteps")
    ->select(
        "subprocess_id",
        DB::raw("MAX(CASE WHEN step_no = '1' THEN s_name END) AS first_step"),
        DB::raw("MAX(CASE WHEN step_no = '2' THEN s_name END) AS second_step"),
        DB::raw("MAX(CASE WHEN step_no = '3' THEN s_name END) AS third_step"),
        DB::raw("MAX(CASE WHEN step_no = '4' THEN s_name END) AS fourth_step"),
        DB::raw("MAX(CASE WHEN step_no = '5' THEN s_name END) AS fifth_step"),
        DB::raw("MAX(CASE WHEN step_no = '6' THEN s_name END) AS sixth_step")
    )
    ->where("subprocess_id", 8010)
    ->groupBy("subprocess_id")
    ->get();
lx0bsm1f

lx0bsm1f2#

删除max函数后面的空格。
而不是:

max (case

用途:

max(case

要使空间工作,您需要使用--sql-mode=IGNORE_SPACE。参见docmentation

相关问题