比较mysql中的2列

时间:2017-01-30 14:04:37

标签: mysql sql

我有2个带有波纹管数据的表(不匹配的数据可以是amount1或amount2)

date        ID  amount1   amount2
11-2-16     2     2         0
11-2-16     1     5         11
11-2-16     3     0         9
12-2-16     2     4         0
12-2-16     1     4         0

表2

Bdate     BID  Bamount1   Bamount2
11-2-16     1     5         11
11-2-16     2     1         0
11-2-16     3     0         6
12-2-16     1     4         0
12-2-16     2     1         0

我需要的是显示两个表中不匹配的数据,如下所示

Date       id     Amoun1   Bamount1        Amount2     Bamount
11-2-16     2        2        1        
11-2-16     3                                  9          6
12-2-16     2        4        1                           

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

创建表/插入数据

CREATE TABLE Table1
    (`date` VARCHAR(7), `ID` INT, `amount1` INT, `amount2` INT)
;

INSERT INTO Table1
    (`date`, `ID`, `amount1`, `amount2`)
VALUES
    ('11-2-16', 2, 2, 0),
    ('11-2-16', 1, 5, 11),
    ('11-2-16', 3, 0, 9),
    ('12-2-16', 2, 4, 0),
    ('12-2-16', 1, 4, 0)
;


CREATE TABLE Table2
    (`Bdate` VARCHAR(7), `BID` INT, `Bamount1` INT, `Bamount2` INT)
;

INSERT INTO Table2
    (`Bdate`, `BID`, `Bamount1`, `Bamount2`)
VALUES
    ('11-2-16', 1, 5, 11),
    ('11-2-16', 2, 1, 0),
    ('11-2-16', 3, 0, 6),
    ('12-2-16', 1, 4, 0),
    ('12-2-16', 2, 1, 0)
;

<强>查询

加入日期和ID并使用where过滤掉字段不匹配的位置。

SELECT 
   Table1.date AS "Date"
 , Table1.id
 , (CASE WHEN Table1.Amount1 > 0 THEN Table1.Amount1 ELSE NULL END) AS "Amount1"
 , (CASE WHEN Table2.Bamount1 > 0 THEN Table2.Bamount1 ELSE NULL END) AS "Bamount1"
 , (CASE WHEN Table1.amount2 > 0 THEN Table1.amount2 ELSE NULL END) AS "amount2"
 , (CASE WHEN Table2.Bamount2 > 0 THEN Table2.Bamount2  ELSE NULL END) AS "Bamount2"  
FROM 
 Table1 
INNER JOIN
 Table2
ON
   Table1.date = Table2.Bdate 
 AND
   Table1.id = Table2.Bid
WHERE
     Table1.amount1 != Table2.Bamount1
   OR
     Table1.amount2 != Table2.Bamount2 

<强>结果

Date         id  Amount1  Bamount1  amount2  Bamount2  
-------  ------  -------  --------  -------  ----------
11-2-16       2        2         1   (NULL)      (NULL)
11-2-16       3   (NULL)    (NULL)        9           6
12-2-16       2        4         1   (NULL)      (NULL)

答案 1 :(得分:0)

您想要两者都不匹配的行,还是只需要不匹配的行。如果是第二个,使用它,如果是第一个,则将或更改为AND

select * from table1 as t1 join table2 as t2 on t1.ID = t2.BID where t1.amount1 != t2.Bamount1 or t2.amount2 != t2.Bamount2