我在SQL查询中遇到问题以获取正确的和值,我显示了我的数据库表,请帮助解决此问题。
&page
我的代码点火器代码如下,
stock
+-------------+-----------+----------------+
| stock_id | order_id | stock_series |
+-------------+-----------+----------------+
| 25 | 7 | 10001 |
| 26 | 7 | 10002 |
| 27 | 7 | 10003 |
| 28 | 9 | 10004 |
| 29 | 9 | 10005 |
+-------------+-----------+----------------+
stock_details
+-------------+-----------+----------------+----------------+
| stock_id | order_id | item_id | item_rcv_qty |
+-------------+-----------+----------------+----------------+
| 25 | 7 | 3 | 2 |
| 25 | 7 | 1 | 10 |
| 26 | 7 | 1 | 3 |
| 27 | 7 | 1 | 2 |
| 28 | 9 | 4 | 5 |
| 28 | 9 | 1 | 5 |
| 29 | 9 | 4 | 5 |
| 29 | 9 | 1 | 5 |
+-------------+-----------+----------------+----------------+
purchase_orders_details
+-------------+-----------+----------------+
| order_id | item_id | item_qty |
+-------------+-----------+----------------+
| 7 | 1 | 2 |
| 8 | 1 | 5 |
| 7 | 1 | 10 |
| 9 | 1 | 10 |
| 7 | 3 | 10 |
| 9 | 4 | 20 |
+-------------+-----------+----------------+
返回结果是
$stock_id = 25;
$result = $this->db->select('
s.stock_id,
st.item_id,
SUM(pd.item_qty) AS item_qty,
SUM(st.item_rcv_qty) AS rcv_qty
')->from('stock s')
->join('stock_details st', 'st.stock_id = s.stock_id', 'left')
->join('purchase_orders_details pd', 'pd.order_id = st.order_id AND pd.item_id = st.item_id', 'left')
->group_by(array('st.item_id', 'st.stock_id'))
->where('s.stock_id', $stock_id)
->get();
$count = $result->num_rows();
if($count > 0){
$result = $result->result();
return $result;
}
Array
(
[0] => stdClass Object
(
[stock_id] => 25
[item_id] => 1
[item_qty] => 15
[rcv_qty] => 20
)
[1] => stdClass Object
(
[stock_id] => 25
[item_id] => 3
[item_qty] => 2
[rcv_qty] => 2
)
)
必须为10,但数组rcv_qty
中的rcv_qty
是10
,您可以在我的数据库表stock_details
中看到第二行stock_id
为25
}和item_rcv_qty
是10
,但是数组显示为20
请任何人解决这个问题 谢谢。
答案 0 :(得分:0)
原因是当您在stock_details
表上加入purchase_orders_details
时,purchase_orders_details
中有2条与stock_id=25
对应的记录,因此{{1} }将在2条记录上运行,而不只是1条,总结SUM(st.item_rcv_qty)
两次。
如果每个item_rcv_qty
- stock_details
组合stock_id
只有1条记录(如示例数据所示),那么只需使用min()/ max()/ any_data ()函数代替该列上的sum()以获得10:
order_id