如何删除子查询返回的所有记录?

时间:2016-09-22 10:25:47

标签: sql oracle sql-delete

我想删除某个查询返回的所有记录,但我无法找到正确的方法来执行此操作。然而,我尝试DELETE FROM mytable WHERE EXISTS (subquery)删除了表中的所有记录,而不仅仅是子查询选择的记录。

我的子查询看起来像这样:

SELECT 
MAX(columnA) as columnA,
-- 50 other columns
FROM myTable 
GROUP BY
-- the 50 other columns above
having count(*) > 1;

这应该很容易,但我的思绪现在就被卡住了。我很感激任何建议。

编辑:columnA不是唯一的(该表中的其他列也不是全局唯一的)

3 个答案:

答案 0 :(得分:2)

据推测,您想使用in

DELETE FROM myTable
    WHERE columnA IN (SELECT MAX(columnA) as columnA
                      FROM myTable 
                      GROUP BY -- the 50 other columns above 
                      HAVING count(*) > 1
                     );

这假设表中的columnA 全局唯一。否则,你将不得不更努力地工作。

DELETE FROM myTable t
    WHERE EXISTS (SELECT 1
                  FROM (SELECT MAX(columnA) as columnA,
                               col1, col2, . . .
                        FROM myTable 
                        GROUP BY -- the 50 other columns above 
                        HAVING count(*) > 1
                       ) t2
                  WHERE t.columnA = t2.columnA AND
                        t.col1 = t2.col1 AND
                        t.col2 = t2.col2 AND . . .
                 );

而且,如果任何列都有NULL值,即使这个也不起作用(尽管可以很容易地修改条件来处理这个问题)。

答案 1 :(得分:0)

如果您需要删除表的所有行,使得给定字段的值在查询结果中,您可以使用类似

的内容
delete table
my column in ( select column from ...)

答案 2 :(得分:0)

如果唯一性仅由一组列保证,则为另一种解决方案:

delete table1 where (col1, col2, ...) in (
    select min(col1), col2, ...
    from table1 
    where...
    group by col2, ...
)

Null值将被忽略,不会被删除。

要实现这一目标,请尝试类似

的内容
with data (id, val1, val2) as 
(
select 1, '10', 10 from dual union all
select 2, '20', 21 from dual union all
select 2, null, 21 from dual union all
select 2, '20', null from dual 
)
-- map null values in column to a nonexistent value in this column
select * from data d where (d.id, nvl(d.val1, '#<null>')) in 
(select dd.id, nvl(dd.val1, '#<null>') from data dd)
相关问题