SQL查询在两个表中查找不同的值?

时间:2011-10-11 19:27:33

标签: sql distinct

Table 1              Table 2
Number | Code        Code | Description
1234     A           A      Something
1235     B           C      Something else
1246     C           D      Something other
1247     A
1248     B
1249     A

我想找到不同的Code值并得到这样的回报:

1  |  2
-------
A     A
B
C     C
      D

我无法弄清楚如何编写一个可以返回上述结果的SQL查询。任何人都有这样或类似的查询经验吗?

6 个答案:

答案 0 :(得分:13)

在适当的RDBMS中:

SELECT
   T1.Code, T2.Code
FROM
   (SELECT DISTINCT Code FROM Table1) T1
   FULL OUTER JOIN
   (SELECT DISTINCT Code FROM Table2) T2
              ON T1.Code = T2.Code

在MySQL中... UNION删除重复项

SELECT
   T1.Code, T2.Code
FROM
   Table1 T1
   LEFT OUTER JOIN
   Table2 T2 ON T1.Code = T2.Code
UNION
SELECT
   T1.Code, T2.Code
FROM
   Table1 T1
   RIGHT OUTER JOIN
   Table2 T2 ON T1.Code = T2.Code

答案 1 :(得分:2)

您要找的是full outer join

select a.code as code_1,b.code as code_2
from(
  select code
  from table1
  group by 1
)a
full outer join(
  select code
  from table2 
  group by 1
)b
using(code)
order by 1;

答案 2 :(得分:2)

在标准SQL中,使用关系运算符并避免使用空值:

SELECT Code AS col_1, Code AS col_2
  FROM Table_1
INTERSECT
SELECT Code AS col_1, Code AS col_2
  FROM Table_2

UNION

SELECT Code AS col_1, 'missing' AS col_2
  FROM Table_1
EXCEPT
SELECT Code AS col_1, 'missing' AS col_2
  FROM Table_2

UNION

SELECT 'missing' AS col_1, Code AS col_2
  FROM Table_2
EXCEPT
SELECT 'missing' AS col_1, Code AS col_2
  FROM Table_1;

再次在标准SQL中,这次使用MySQL实际支持的构造:

SELECT Code AS col_1, Code AS col_2
  FROM Table_1
 WHERE EXISTS (
               SELECT * 
                 FROM Table_2
                WHERE Table_2.Code = Table_1.Code
              )  

UNION

SELECT Code AS col_1, 'missing' AS col_2
  FROM Table_1
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM Table_2
                    WHERE Table_2.Code = Table_1.Code
                  )  
UNION

SELECT 'missing' AS col_1, Code AS col_2
  FROM Table_2
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM Table_1
                    WHERE Table_1.Code = Table_2.Code
                  );

答案 3 :(得分:0)

这实际上看起来像两个外连接的UNION。试试这个:

SELECT t1.Code, t2.Code
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON t1.Code

UNION

SELECT t1.Code, t2.Code
FROM Table1 AS t1
RIGHT JOIN Table2 AS t2 ON t1.Code

ORDER BY 1, 2

UNION操作只会保留不同的值。

答案 4 :(得分:0)

诀窍是从两个表中获取不同的值,如下所示:

SELECT a.Code, b.code
FROM
( --Get the DISTICT Codes from all sets
    SELECT Distinct Code from Table1
    UNION SELECT Distinct Code from Table2
) x Left JOIN
Table1 a ON x.code = a.Code LEFT JOIN
Table2 b ON x.code = b.Code

答案 5 :(得分:0)

SELECT  
   ct.ct_id, 
   ct.pd_id, 
   ct.ct_qty, 
   pd.product_name, 
   pd.price, 
   src.service_id, 
   src.service_name, 
   src.service_charge, 
   src.service_quantity
FROM 
   cart ct, 
   product pd, 
   service src 
WHERE ct_session_id = '$sid' 
LIMIT 1