我需要匹配同一个表中的值并显示它们的减法。但是,某些值可能不匹配(因为它们不存在),在这种情况下,我应该显示null或零。
Table purchase_items
---------------------
ID | purchase_id | item_id | quantity
1 103 1 10
2 103 2 5
3 103 3 20
4 104 1 5
5 104 2 5
所需的输出是:
item_id | Original quantity | New quantity | Total
1 10 5 5
2 5 5 0
3 20 null/0 20
目前我无法提供最后一行。通过下面的查询,我只能重现:
item_id | Original quantity | New quantity | Total
1 10 5 5
2 5 5 0
SELECT
original.quantity AS `Original quantity`,
new.quantity AS `New quantity`,
(original.quantity - new.quantity) AS total
FROM
purchase_items AS original,
purchase_items AS new
WHERE
original.purchase_id = 103 AND new.purchase_id = 104 AND original.item_id = new.item_id
我确实意识到问题在original.item_id = new.item_id
范围内,但我怎样才能解决这个问题呢?
编辑:看来我的帖子令人困惑。我会尝试以更好的方式解释它。
我试图理解上一份文件中销售的商品,并与当前文件中销售的商品进行比较。
我的表格如下:
Table purchase_items
---------------------
ID | purchase_id | item_id | quantity
1 103 1 10
2 103 2 5
3 103 3 20
4 104 1 5
5 104 2 5
根据此值,您可以从第1项(,同样适用于第2项)了解以下情况:
因此,输出必须是:
item_id | Original quantity | New quantity
1 10 5
2 5 5
现在,如果您查看表格,那么第3项,已在购买凭证103中出售,但未在购买凭证104中出售!话虽如此,输出应该是
item_id | Original quantity | New quantity
1 10 5
2 5 5
3 20 0/null
忘记减法,因为如果需要,我可以在PHP中完成。
请看一下 SQLFiddle 。
答案 0 :(得分:0)
USE sandbox;
/*
create Table purchase_items
(ID int, purchase_id int, item_id int, quantity int);
insert into purchase_items
values
(1, 1, 1, 10),
(2, 1, 2, 5 ),
(3, 1, 3, 20),
(4, 2, 1, 5),
(5, 2, 2, 5)
;
item_id | Original quantity | New quantity | Total
1 10 5 5
2 5 5 0
3 20 null/0 20
*/
select p1.id,p1.quantity as old_quantity,p2.quantity as new_quantity,
case
when p2.quantity is null then p1.quantity
else p1.quantity - p2.quantity
end as total
from purchase_items p1
left outer join purchase_items p2 on p2.purchase_id = p1.purchase_id + 1 and p2.item_id = p1.item_id
where p1.purchase_id = 1
答案 1 :(得分:0)
使用左连接有帮助,正如我在y评论中写的那样。此查询为yu提供了正确的结果:
SELECT original.item_id,
original.quantity AS `Original quantity`,
new.quantity AS `New quantity`,
(original.quantity - new.quantity) AS total
FROM
purchase_items AS original left join
purchase_items AS new on original.item_id = new.item_id
and
original.purchase_id = 103 AND new.purchase_id = 104
group by original.item_id
正如您在SQL-Fiddle
中所看到的