phpmyadmin 用于从两个表中减去值的MySQL查询

hjzp0vay  于 2022-11-09  发布在  PHP
关注(0)|答案(1)|浏览(155)

你好我有这张table

Table A
ID  Name   Price QTY
1   name1  1000  10
2   name2  1200  5

Table B
ID  Name   Price QTY
1   name1  1000  2

我想实现

Table C
ID  Name   Price QTY
1   name1  1000  8
2   name2  1200  5

用我的查询SELECT DISTINCT ta.name, ta.price,(ta.quantity - tb.quantity) AS quantity, FROM TableA AS ta INNER JOIN TableB AS tb ON ta.id = tb.id
我得到的是

Table C
ID  Name   Price QTY
1   name1  1000  8
2   name2  1200  3

很抱歉我真的想不出一个方法来实现我想要的。谢谢你的帮助。

1szpjjfi

1szpjjfi1#

您的查询实际上只得到一行而不是两行:

-- result set

# name, price, quantity

name1, 1000, 8

根据您的预期输出,我们可以使用:

SELECT  ta.ID, ta.name, ta.price, ifnull((ta.QTY - tb.QTY),ta.QTY) AS quantity 
FROM TableA AS ta 
LEFT JOIN TableB AS tb 
ON ta.name = tb.name and ta.price=tb.price;
-- result set:

# ID, name, price, quantity

1, name1, 1000, 8
2, name2, 1200, 5

这是我可以为您的更新请求提供的最后一个更新答案。如果它不满足,请考虑激发一个新问题。

-- Supposing your latest tables have the following data.
insert TableA values
(1 ,  'name1' , 1000 , 10)
,(2 ,  'name2' , 1200 , 5);
insert TableB values
(1 ,  'name1' , 1000 , 2),
(2 , 'name2', 1000 , 3)
;

-- You probably want this:
SELECT ta.ID, ta.name, ta.price, ifnull((ta.QTY - tb.QTY),ta.QTY) AS quantity 
FROM TableA AS ta 
LEFT JOIN TableB AS tb 
ON ta.name = tb.name and ta.price=tb.price
union
SELECT  Id , name , price , QTY 
from TableB t
where not exists (select * from TableA where t.name=name and t.price=price)
;

-- result set:

# ID, name, price, quantity

1, name1, 1000, 8
2, name2, 1200, 5
2, name2, 1000, 3

相关问题