表A和表B中的数据之间的差异

时间:2016-06-27 13:44:32

标签: sql database oracle

让我们假设我们正在使用Oracle数据库:

表A包含列:价格,价格表,货币。 表B包含列:价格,价格表,货币,状态。

示例数据:

$.param(data)

我想找到表A中表B中没有的行。

Table A 

price, pricelist, currency
123 , PL_10122016, EUR
111 , PL_10122016, GBP
141 , PL_10122016, USD

Table B 

price, pricelist, currency,status
123 , PL_10122016, EUR,0
111 , PL_10122016, GBP,0
143 , PL_10122016, USD,0

3 个答案:

答案 0 :(得分:1)

使用减号

WITH tablea  (price, pricelist, currency) AS
(SELECT 123 , 'pl_10122016', 'eur' FROM dual UNION ALL
SELECT 111 , 'pl_10122016', 'gbp' FROM dual  UNION ALL
SELECT 141 , 'pl_10122016', 'usd' FROM dual )
,tableb (price, pricelist, currency,status) AS 
(SELECT 123 , 'pl_10122016', 'eur',0 FROM dual  UNION ALL
SELECT 111 , 'pl_10122016', 'gbp',0  FROM dual UNION ALL
SELECT 143 , 'pl_10122016', 'usd',0 FROM dual )
SELECT price , pricelist , currency  FROM tablea
MINUS
SELECT price , pricelist , currency  FROM tableb;

Result:
PRICE   PRICELIST   CURRENCY
141 pl_10122016 usd

使用左连接

WITH tablea  (price, pricelist, currency) AS
(SELECT 123 , 'pl_10122016', 'eur' FROM dual UNION ALL
SELECT 111 , 'pl_10122016', 'gbp' FROM dual  UNION ALL
SELECT 141 , 'pl_10122016', 'usd' FROM dual )
,tableb (price, pricelist, currency,status) AS 
(SELECT 123 , 'pl_10122016', 'eur',0 FROM dual  UNION ALL
SELECT 111 , 'pl_10122016', 'gbp',0  FROM dual UNION ALL
SELECT 143 , 'pl_10122016', 'usd',0 FROM dual )
SELECT a.*
FROM tablea a 
LEFT JOIN tableb b
  ON  a.price = b.price AND a.pricelist = b.pricelist AND a.currency = b.currency
  WHERE b.price IS NULL AND b.pricelist IS NULL AND b.currency IS NULL;

Result:
PRICE   PRICELIST   CURRENCY
141 pl_10122016 usd

您可以使用RIGHT JOIN和FULL OUTER JOIN

进行相同的操作

答案 1 :(得分:0)

您在询问之前是否搜索过stackoverflow?已有类似问题的答案。 Take a look here

他的解决方案:

a1 <- data.frame(a = 1:5, b=letters[1:5])
a2 <- data.frame(a = 1:3, b=letters[1:3])

rows.in.a1.that.are.not.in.a2  <- function(a1,a2)
{
    a1.vec <- apply(a1, 1, paste, collapse = "")
    a2.vec <- apply(a2, 1, paste, collapse = "")
    a1.without.a2.rows <- a1[!a1.vec %in% a2.vec,]
    return(a1.without.a2.rows)
}
rows.in.a1.that.are.not.in.a2(a1,a2)

答案 2 :(得分:0)

Select A.price, A.pricelist, A.currency
    FROM TableA A 
    LEFT JOIN TableB B
      ON  A.price = B.price  
      AND A.pricelist = B.pricelist
      AND A.currency = B.currency

在此之前,您有来自TableB的匹配行和TableA中的所有行(匹配和不匹配)。 followig条件会将结果减少到只有不匹配的行:

      WHERE B.price is NULL
      AND B.pricelist is NULL
      AND B.currency is NULL