laravel原始语法中的子查询

时间:2018-12-03 19:47:00

标签: php mysql laravel eloquent

我正在尝试使用DB::raw('raw sql query')来运行以下查询:

    $rates = DB::raw('SELECT
           mid,
           x.qty_t/x.qty_total,
           x.qty_t,
           x.qty_total,
           FROM
              (SELECT
                 mid,
                 SUM(CASE WHEN (mtc="qty") THEN 1 ELSE 0 END) AS qty_total,
                 SUM(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_t,
                 STDDEV(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_sd
            FROM
               t_r
            GROUP BY
               mid) x')->get();

(SELECTmidmtc的{​​{1}}之后出现语法错误。

如何使用t_r使它正常工作?

1 个答案:

答案 0 :(得分:3)

您需要在其周围包装DB :: select。这样的事情应该起作用。

$rates = DB::select(DB::raw('SELECT
       mid,
       x.qty_t/x.qty_total,
       x.qty_stddev,
       x.qty_total,
       FROM
          (SELECT
             mid,
             SUM(CASE WHEN (mtc="qty") THEN 1 ELSE 0 END) AS qty_total,
             SUM(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_t,
             STDDEV(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_sd
        FROM
           t_r
        GROUP BY
           mid) x'))->get();