1

新手问题。我想做类似的事情:

SELECT c1,c2,c3 FROM TABLE t1
UNION
SELECT c1,c2,c3 FROM TABLE t2 WHERE t1.c1 IS NOT NULL AND t1.c2 IS NULL;

所以如果我有 t1:

c1|c2|c3
1 | a|v1
2 | b|v2

和 t2:

c1|c2|c3
1 | a|v3
2 | b|v4
2 | c|v5
3 | d|v6

我会得到:

c1|c2|c3
1 | a|v1
2 | b|v2
2 | c|v5

有人知道该怎么做吗?

4

3 回答 3

2

查询应该如下所示。但是,我不确定它的效率如何。

SELECT 
    T1.c1,
    T1.c2,
    T1.c3
FROM T1
UNION     
SELECT 
    T2.c1,
    T2.c2,
    T2.c3
FROM T2 
WHERE ((T2.c1,T2.c2) NOT IN (SELECT t1.c1,t1.c2 FROM t1)) AND 
(T2.c1 IN (SELECT t1.c1 FROM t1))
于 2012-05-10T05:18:59.453 回答
2

根据 SQL Docs,JOINSubQueries. 试试这个:

 SELECT c1, c2, c3
 FROM   t1
 UNION
 SELECT b.c1, b.c2, b.c3
 FROM   t1 a inner join t2 b ON
         (a.c1 = b.c1) and (a.c1 = b.c1)
 WHERE  (b.c1,b.c2) NOT IN (SELECT c1,c2 FROM t1)

要证明,请参见此处:http ://sqlfiddle.com/#!2/50a4e/23

于 2012-05-10T05:24:54.230 回答
0
select t2.c1,t2.c2,t2.c3 
from t1,t2 
where t1.c1=t2.c2;
于 2012-05-10T05:30:57.037 回答