【发布时间】:2020-04-01 15:24:11
【问题描述】:
我有一个 MySQL 数据库来管理项目的接收和问题。其中一张表包括如下。同一商品有不同的价格。
store_update_stock_details 表
+-------------------------+------+-----+------------+
| update_stock_details_id | item | qty | unit_price |
+-------------------------+------+-----+------------+
| 1 | 4 | 8 | 35.00 |
| 2 | 4 | 30 | 38.50 |
| 3 | 4 | 20 | 42.00 |
| 4 | 4 | -11 | 38.50 |
| 5 | 4 | -1 | 38.50 |
| 6 | 4 | -1 | 35.00 |
| 7 | 4 | -1 | 35.00 |
| 8 | 4 | -1 | 35.00 |
| 9 | 4 | -1 | 35.00 |
| 10 | 4 | -4 | 35.00 |
+-------------------------+------+-----+------------+
(-) 符号表示表中的问题。然后我需要在执行问题后按如下方式获取可用余额。
+------+-----+------------+
| item | qty | unit_price |
+------+-----+------------+
| 4 | 18 | 38.50 |
| 4 | 20 | 42.00 |
+------+-----+------------+
我使用以下查询来做到这一点。
public function isExistProduct($q)
{
if (!empty($q)) {
$this->db->select("store_item.*, store_update_stock.*, sum(qty) as qty, unit_price");
$this->db->from('store_update_stock_details');
$this->db->join('store_update_stock', 'store_update_stock_details.update_stock_id=store_update_stock.update_stock_id');
$this->db->join('store_item', 'store_update_stock_details.item=store_item.item_id');
$this->db->where("store_update_stock.status=1 and store_item.item_id= $q");
$this->db->where("store_update_stock_details.qty != 0 ");
$this->db->group_by('store_update_stock_details.unit_price','store_item.item_id');
$q1 = $this->db->get();
if ($q1->num_rows() > 0) {
return $q1->result_array();
}
return 0;
}
}
但函数返回结果如下:
+------+-----+------------+
| item | qty | unit_price |
+------+-----+------------+
| 4 | 0 | 35.00 |
| 4 | 18 | 38.50 |
| 4 | 20 | 42.00 |
+------+-----+------------+
我不需要获取项目不可用 (qty=0) 的余额。我的查询可以更改什么?有人可以帮忙吗?
【问题讨论】:
-
你试过 HAVING sum(qty)>0 吗?
-
为什么是 38.5,而不是 35?
-
请打印_r qi,看看你要在语句中做什么,并检查日志文件错误
标签: mysql codeigniter