如何删除Oracle SQL查询中的重复行

时间:2014-11-17 05:09:04

标签: sql oracle

我有一个查询

SELECT t1.table_id FROM TABLE_ONE t1, COMMON_TABLE cmn
  WHERE
        t1.table_name = 'TEST_ONE'
    AND t1.table_id = cmn.common_id
    AND cmn.column_one > 20
    AND cmn.column_two <= 30
UNION
  SELECT t2.table_id FROM TABLE_ONE t2, COMMON_TABLE cmn
  WHERE
        t2.table_name = 'TEST_TWO'
    AND t2.table_id = cmn.common_id
    AND cmn.column_one > 20
    AND cmn.column_two <= 30
UNION
  SELECT t3.table_id FROM TABLE_ONE t3, COMMON_TABLE cmn
  WHERE
        t3.table_name = 'TEST_THREE'
    AND t3.table_id = cmn.common_id
    AND cmn.column_one > 20
    AND cmn.column_two <= 30
UNION
  SELECT tc1.table_id FROM TABLE_CHILD_ONE tc1, TABLE_ONE t1, COMMON_TABLE cmn
  WHERE
        tc1.table_name = 'TEST_CHILD_ONE'
    AND tc1.table_id = t1.table_id
    AND t3.table_id = cmn.common_id
    AND cmn.column_one > 20
    AND cmn.column_two <= 30

我想删除重复的行

AND cmn.column_one > 20
AND cmn.column_two <= 30

并把它放在最后。你能帮助我吗?如答案中提到的使用连接的问题是,我不确定如何将连接与子表连接。我可以选择使用嵌套选择。但是试图使用连接来获得更好的性能。

2 个答案:

答案 0 :(得分:3)

您可以使用以下连接语法重写此查询:

SELECT DISTINCT t.table_id
FROM   TABLE_ONE t
       JOIN COMMON_TABLE cmn
         ON t.table_id = cmn.common_id
WHERE  t.table_name IN( 'TEST_ONE', 'TEST_TWO', 'TEST_THREE' )
       AND cmn.column_one > 20
       AND cmn.column_two <= 30 

DISTINCT将删除重复的记录。

编辑:

您可以将您的子表格包括在内:

SELECT DISTINCT t.table_id
FROM   TABLE_ONE t
       JOIN COMMON_TABLE cmn
         ON t.table_id = cmn.common_id
       JOIN TABLE_CHILD_ONE tc
         ON t.table_id = tc.table_id
WHERE  ( tc.table_name IN( 'TEST_CHILD_ONE', 'TEST_CHILD_TWO', 'TEST_CHILD_THREE' )
          OR t.table_name IN( 'TEST_ONE', 'TEST_TWO', 'TEST_THREE' ) )
       AND cmn.column_one > 20
       AND cmn.column_two <= 30 

答案 1 :(得分:1)

您可以删除下面的常见限制条件

 SELECT table_id FROM 
    (SELECT t1.table_id, cmn.column_one, cmn.column_two  FROM TABLE_ONE t1, COMMON_TABLE cmn
      WHERE
            t1.table_name = 'TEST_ONE'
    UNION
      SELECT t2.table_id, cmn.column_one, cmn.column_two  FROM TABLE_ONE t2, COMMON_TABLE cmn
      WHERE
            t2.table_name = 'TEST_TWO'
    UNION
      SELECT t3.table_id, cmn.column_one, cmn.column_two  FROM TABLE_ONE t3, COMMON_TABLE cmn
      WHERE
            t3.table_name = 'TEST_THREE') AS MyTable
            WHERE
        column_one > 20
        column_two <= 30