如何通过选择查询更新表

时间:2019-05-21 05:16:57

标签: sql laravel-5 mariadb

我正在使用DB Facade创建一个临时表,然后使用选择查询,我需要根据条件更新临时表中的某些列

DB::update('update table_temp_topcustomer 
            set ordercount = aaa.ordercount 
            from 
            (select count(id) as ordercount,mobileno 
             from order_hdrs 
             group by mobileno 
            ) as aaa
            where table_temp_topcustomer .mobileno = aaa.mobileno
          ');

出现此错误

  

语法错误或访问冲突:1064您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册以获取正确的语法,以在第1行附近使用'from(from(select count(id)as ordercount,mobileno from order_hdrs group by mobileno)'(SQL:update table_temp_topcustomer set ordercount = aaa.ordercount from (选择count(id)作为ordercount,从order_hdrs group中选择mobileno由mobileno)作为aaa)

我该如何实现?

2 个答案:

答案 0 :(得分:1)

UPDATE table_temp_topcustomer JOIN 
        ( SELECT order_hdrs count(*) as ordercount 
              FROM order_hdrs 
              GROUP BY mobileno
        ) AS aaa 
           ON table_temp_topcustomer.mobileno = aaa.mobileno
        SET   table_temp_topcustomer.ordercount = aaa.ordercount 

答案 1 :(得分:0)

我想您不能在单个查询中完成。根据我的理解。首先获取选择结果并循环更新。

您应该尝试以下类似方法。

$result = DB::select('select count(id) as ordercount,mobileno 
                 from order_hdrs 
                 group by mobileno');
foreach($result as $item) {

    DB::update('update table_temp_topcustomer 
               set ordercount = '. $item->ordercount .' 
              where table_temp_topcustomer.mobileno = ' $item->mobileno);
}
相关问题