简体   繁体   English

如何从 MySQL 中的两个表中减去相同的值?

[英]How can I subtract the same values from two tables in MySQL?

I have two tables with the same columns, but one table have more and different values than the other.我有两张具有相同列的表,但一张表的值比另一张表的值更多且不同。 How can I subtract the same values in two tables.如何在两个表中减去相同的值。

Table 1                Table 2
    Name   Number             Name  Number
    Dan    5                  Dan   2
    Jon    3                  Dev   1
    Dev    2
    Gin    2

How can I query to have the result:如何查询以获得结果:

    Name   Number            
    Dan    3                    
    Jon    3                    
    Dev    1
    Gin    2

You'll need a LEFT JOIN :你需要一个LEFT JOIN

SELECT table1.name, 
        table1.num-IFNULL(table2.num,0)
FROM table1 LEFT JOIN table2
ON table1.name=table2.name;

IFNULL() is to replace NULL values with zero(0); IFNULL()是用零(0)替换NULL值; returned from table on the right side of the LEFT JOIN ( table2 ) due to non-existing values.由于不存在的值,从LEFT JOIN ( table2 ) 右侧的表返回。

Read more about MySQL JOIN .阅读更多关于MySQL JOIN的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM