2017-01-30 100 views
0

IM具有2代表與波紋管的數據(不匹配數據可以是amount1或AMOUNT2)在MySQL比較2列

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       

感謝您的幫助

+0

請詳細說明 「這是不匹配」。目前尚不清楚你的意思 – apomene

+0

不符合數據可以在金額1或金額2 –

回答

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並使用哪裏來過濾出字段不匹配的地方。

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) 
+0

謝謝你,這是工作很好。 –

0

你是否想要兩行不匹配的行或者哪一行不行。如果它的第二個,利用這一點,如果第一,改變或到與

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