我提出了查询:
SELECT ad.spec_id, ad.height_id, ad.size_id, (SUM(ad.qty)+SUM(md.qty)) as qty, SUM(ad.qty) as arrival_qty, SUM(md.qty) as movement_qty, a.warehouse_id
FROM arrival_data ad, movement_data md, arrivals a, movements m
WHERE ad.size_id= md.size_id
AND ad.height_id = md.height_id
AND ad.spec_id = md.spec_id
AND ad.arrival_id = a.arrival_id
AND m.receiver = a.warehouse_id
AND md.movement_id = m.movement_id
GROUP BY ad.spec_id, ad.size_id, ad.height_id, m.receiver
但当然只有第一个和第二个表具有相同的spec_id,size_id,height_id时才会显示结果。我已经读过加入可以解决这个问题。请帮助解决正确的问题
我通过漫长而缓慢的方法解决了我的任务
$arrival_qty = $this->db->getOne('
SELECT SUM(ad.qty)
FROM arrival_data ad, arrivals a
WHERE ad.arrival_id = a.arrival_id AND ad.spec_id =?i AND ad.size_id =?i AND ad.height_id =?i AND a.warehouse_id = ?i',
$product['spec_id'], $product['size_id'], $product['height_id'], $product['warehouse_id']);
$move_in_qty = $this->db->getOne('
SELECT SUM(md.qty)
FROM movement_data md, movements m
WHERE md.movement_id = m.movement_id AND md.spec_id =?i AND md.size_id =?i AND md.height_id =?i AND m.receiver =?i',
$product['spec_id'], $product['size_id'], $product['height_id'], $product['warehouse_id']);
$move_out_qty = $this->db->getOne('
SELECT SUM(md.qty)
FROM movement_data md, movements m
WHERE md.movement_id = m.movement_id AND md.spec_id =?i AND md.size_id =?i AND md.height_id =?i AND m.sender =?i',
$product['spec_id'], $product['size_id'], $product['height_id'], $product['warehouse_id']);
$invoices_qty = $this->db->getOne('
SELECT SUM(i.qty)
FROM invoice_data i, invoices m
WHERE i.invoice_id = m.invoice_id AND i.spec_id =?i AND i.size_id =?i AND i.height_id =?i AND m.warehouse_id =?i',
$product['spec_id'], $product['size_id'], $product['height_id'], $product['warehouse_id']);
$arrival_qty = (!empty($arrival_qty)) ? $arrival_qty : '0';
$products[$key]['qty'] = $arrival_qty + $move_in_qty - $move_out_qty - $invoices_qty;
也许有人可以通过一个查询给我变体
答案 0 :(得分:0)
我真的不知道,你想要做什么。但我可以找到小错误,你已经在SELECT列表中添加了一个带有聚合函数的a.warehouse_id但是没有在GROUP BY子句中添加
所以,你可能会收到这样的错误..
列'a.warehouse_id'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
要解决此问题,请在GROUP BY子句中添加a.warehouse_id或将其从SELECT列表中删除
答案 1 :(得分:0)
即使列名不同,这种语法也能正常工作: 从中选择sum(x) ( 从arrival_data中选择sum(qty)为x 联合所有 从和move_data中选择sum(qty)为x ) 作为x;