2013-02-24 94 views
1

之間的差異記錄這是較早question這裏的延伸的Mysql只返回有兩個表

我有兩個表,昨天和今天,並在每個表中有兩列

StockNumber, StockLevel 

如何我找出

  1. 只有在他們StockLevel的
  2. 返回自動對焦差異StockNumbers染StockNumber & StockLevel值

例如:

各國表:

StockNumber, StockLevel 
ABC, 10 
CBA,5 
123,5 

昨天表:

StockNumber, StockLevel 
ABC, 9 
CBA,5 
123,10 

返回以下無線

StockNumber, StockLevel 
ABC, 10 
123, 5 

現在注意StockNumber「ABC」正在返回今天的值10,StockNumber「123」也正在返回今天的值5和StockNumber「CBA」沒有變化並且沒有被返回。

非常感謝,

馬特

回答

3

這將做它的股票,這兩天都存在;

SELECT t.StockNumber, t.StockLevel 
FROM today t 
JOIN yesterday y 
    ON t.StockNumber=y.StockNumber 
AND t.StockLevel <> y.StockLevel 

如果您(如您之前的問題)也希望今天包括新股票;

SELECT t.StockNumber, t.StockLevel 
FROM today t 
LEFT JOIN yesterday y 
    ON t.StockNumber = y.StockNumber 
WHERE y.StockNumber IS NULL 
    OR t.StockLevel <> y.StockLevel 

An SQLfiddle to test both with

+0

後來的查詢做了伎倆,謝謝 – 2013-02-24 16:42:37

0

可以聯接StockNumber表和選擇這些行WHERE NOT A.StockLevel = B.StockLevel

0

這有點棘手,因爲你可能在兩個表中有不同的項目。我建議一個工會所有和團體由這個:

select stockNumer, 
     max(case when which = 'yesterday' then stocklevel end) as yesterdaylevel, 
     max(case when which = 'today' then stocklevel end) as todaylevel 
from ((select StockNumber, StockLevel, 'yesterday' as which 
     from yesterday 
    ) union all 
     (select StockNumber, StockLevel, 'today' as which 
     from today 
    ) 
    ) t 
group by stockNumber 
having min(StockLevel) <> max(stockLevel) and count(*) = 2 
0
select T.StockNumber, T.StockLevel 
from Today as T 
left join Yesterday as Y 
on T.StockNumber = Y.StockNumber 
WHERE T.StockLevel <> Y.StockLevel 

的結果在這裏玩:http://sqlfiddle.com/#!2/367b0/3/0

0

下面的查詢將返回或者是不同的(由StockLevel)從昨天的股票,或不存在昨天(這是什麼LEFTIS NULL是):

SELECT Today.* 
FROM Today LEFT JOIN Yesterday 
    ON Today.StockNumber = Yesterday.StockNumber 
WHERE 
    Today.StockLevel <> Yesterday.StockLevel 
    OR Yesterday.StockLevel IS NULL