Mysql仅返回两个表之间存在差异的记录

时间:2013-02-24 16:14:40

标签: mysql sql

这是早期question此处

的扩展

我有两张桌子,昨天和今天,每张桌子都有两列

StockNumber, StockLevel

我如何找到

  1. 只有StockLevel中存在差异的StockNumbers
  2. 退回受影响的StockNumber& StockLevel值
  3. 例如:

    今日表:

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

    昨天表:

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

    返回以下wi

    StockNumber, StockLevel
    ABC, 10
    123, 5
    

    现在注意到StockNumber“ABC”今天返回值10,StockNumber“123”也返回今天的值5,StockNumber“CBA”没有变化,也没有返回。

    非常感谢,

    马特

5 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以加入StockNumber上的表格并选择那些行WHERE NOT A.StockLevel = B.StockLevel

答案 2 :(得分:0)

这有点棘手,因为您可能在两个表中有不同的项目。我建议使用union all和group by:

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

答案 3 :(得分: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

答案 4 :(得分:0)

以下查询将返回与昨天不同(从StockLevel开始)或昨天不存在的股票(这是LEFTIS NULL的用途):< / p>

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