union查询出来之后,字段值互换了
开发环境:PHP7.2 win8.1 laravel5.4
先读A表(主表)数据,再读B表(明细表)数据,最后$a->unionAll($b)
最后是sum
处理里面的一个字段,结果发现最后的数据不对
开始一步一步研究
A表打印出来的数据如下(数据量较多,只摘取了其中一段)
"stock_id" => "1629785859861559552"
"store_id" => "1629780977976914944"
"product_id" => "1629783010779894016"
"supplier_id" => "1629780382641606144"
"stock" => "49.0000"
"remaining_month" => 0
B表打印出来的数据
"stock_id" => "388581679721879368"
"product_id" => "1629783010779894016"
"store_id" => "1629780977976914944"
"supplier_id" => "1629780382641606144"
"stock" => "-20.0000"
"remaining_month" => 0
注意上面有一个product_id为1629783010779894016
,这里是正确的,在数据库中也是对的
当我执行了unionAll
之后,结果却不对,执行代码如下:
$unionRes = $a->unionAll($b);
// 原因出来在这里,我打印完联合后的数组后,发现数据不一致了
dump($unionRes->get()->toArray());
$sss = DB::table(DB::raw("({$unionRes->toSql()}) AS item"))
->mergeBindings($unionRes->getQuery())
// 另一种写法 --没有生效
// ->addBinding($unionRes->getBindings())
->select(
'product_id',
DB::raw('sum(stock) as stock')
)
->groupBy('product_id')
->get();
原本是product_id为1629783010779894016
的,在$unionRes
的结果集中却错行显示在了store_id
字段中,从这里导致了就算结果出现了问题
"stock_id" => "388581679721879368"
"store_id" => "1629783010779894016"
"product_id" => "1629780977976914944"
"supplier_id" => "1629780382641606144"
"stock" => "-20.0000"
"remaining_month" => 0
打印了一下原本两个结果集中的stock
字段的数据,是正确的结果
"A结果集中的stock相加后:" 99.0
"B结果集中的stock相加后:" -29.0
"两个相加:" 70.0
想知道出现这个问题的原因,感谢!
你的 Union 联合表中的字段顺序也要一致吧!!!