如何在多个父表和子表的Oracle SQL查询中删除重复的行

时间:2014-11-17 16:40:41

标签: sql oracle join

昨天我发布了一个关于重复oracle sql查询的问题。

How to remove repeated lines in an Oracle SQL query

如果我有多个父表和子表,如何使用JOIN修改SQL查询?

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_TWO 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_THREE 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 cmn.column_one > 20
    AND cmn.column_two <= 30
UNION
  SELECT tc2.table_id FROM TABLE_CHILD_TWO tc2, TABLE_TWO t2, COMMON_TABLE cmn
  WHERE
        tc2.table_name = 'TEST_CHILD_TWO'
    AND tc2.table_id = t2.table_id
    AND cmn.column_one > 20
    AND cmn.column_two <= 30

我想删除重复的行

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

3 个答案:

答案 0 :(得分:3)

USE UNION并从所有表中获取值,然后使用COMMON_TABLE执行一次JOIN

SELECT table_id 
FROM 
(
   SELECT t1.table_id FROM TABLE_ONE t1 
   WHERE  t1.table_name = 'TEST_ONE'
   UNION 
   SELECT t2.table_id FROM TABLE_TWO t2
   WHERE  t2.table_name = 'TEST_TWO'
   UNION
   SELECT tc1.table_id FROM TABLE_CHILD_ONE tc1
   JOIN TABLE_ONE t1
   ON tc1.table_name = 'TEST_CHILD_ONE'
   AND tc1.table_id = t1.table_id
) T
JOIN COMMON_TABLE cmn
ON T.table_id = cmn.common_id
AND cmn.column_one > 20
AND cmn.column_two <= 30 

答案 1 :(得分:0)

你试过这个吗?

select table_id
from 
(
select table_id, cmn.column_one, cmn.column_two
etc
) derived_table
where column_one > 20
and column_two <= 30

答案 2 :(得分:0)

您应该使用UNION ALL,除非您确实需要UNION确实提供的数据合并,并且会受到性能下降。

(调整了加入条件 - 不再是AND t3.table_id = cmn.common_id的三倍)。

由于您的数据错综复杂,只需将ALL放在您需要的地方:

SELECT table_id
FROM (
  (SELECT
    t1.table_id
  FROM TABLE_ONE t1
  WHERE t1.table_name = 'TEST_ONE'
  UNION ALL
  SELECT tc1.table_id
  FROM TABLE_CHILD_ONE tc1
  JOIN TABLE_ONE t1
    ON tc1.table_id = t1.table_id
  WHERE tc1.table_name = 'TEST_CHILD_ONE'
  )
  UNION ALL
  (SELECT t2.table_id
  FROM TABLE_TWO t2
  WHERE t2.table_name = 'TEST_TWO'
  UNION ALL
  SELECT tc2.table_id
  FROM TABLE_CHILD_TWO tc2
  JOIN TABLE_TWO t2
    ON tc2.table_id = t2.table_id
  WHERE tc2.table_name = 'TEST_CHILD_TWO'
  )
UNION ALL
SELECT t3.table_id
FROM TABLE_THREE t3
WHERE t3.table_name = 'TEST_THREE') T
JOIN COMMON_TABLE cmn
  ON T.table_id = cmn.common_id
WHERE cmn.column_one > 20
AND cmn.column_two <= 30;