oracle查询在两个表中查找匹配项

时间:2012-09-13 01:16:31

标签: sql database oracle

数据库中有两个表,下面结构相似。

- 我需要TABLE1中的元素列表,其中P1与S3匹配,同时P2与S2匹配。

+            TABLE1           +        +           TABLE2            +
+---------+---------+---------+        +---------+---------+---------+
| P1      | P2      | P3      |        + S1      | S2      | S3      |
+---------+---------+---------+        +---------+---------+---------+
| A       | B       | C       |        | P       | B       | A       |
| B       | B       | C       |        | A       | G       | T       |
| Z       | K       | R       |        | T       | M       | T       |
| T       | S       | L       |        | M       | K       | Z       |
| W       | W       | W       |        | W       | W       | W       |
+---------+---------+---------+        +---------+---------+---------+

所以,结果我得到:

+            RESULT           +
+---------+---------+---------+
| P1      | P2      | P3      |
+---------+---------+---------+
| A       | B       | C       |
| Z       | K       | R       |
| W       | W       | W       |
+---------+---------+---------+

问题:执行此连接,比较和匹配操作的oracle查询是什么。 注意:不鼓励使用循环。

提前致谢...

3 个答案:

答案 0 :(得分:3)

SELECT a.*
FROM TABLE1 a, TABLE2 b
WHERE a.P1 = b.S3 AND a.P2 = b.S2;

答案 1 :(得分:1)

您可以使用INNER JOIN组合两个表格。

SELECT  a.*
FROM    table1 a
        INNER JOIN table2 b
            ON a.P1 = b.S3 AND
               a.P2 = b.S2

<强> CLICK here for more type of Joins (Oracle Docs)

答案 2 :(得分:1)

使用INNER JOIN

SELECT table1.*
FROM table1 INNER JOIN table2 
     ON (table1.P1 = table2.S3 AND table1.P2 = table2.S2);