代码之家  ›  专栏  ›  技术社区  ›  Stephan

postgreSQL select起作用,但delete不起作用

  •  1
  • Stephan  · 技术社区  · 14 年前

    我正试图将以下查询更改为删除返回行的查询。

    SELECT bad_rows.*
    FROM votes as bad_rows
    INNER JOIN(
        SELECT  MIN(id) as min_id, votes.object_id, votes.user_id 
    FROM votes WHERE is_archived=FALSE AND 
         votes.direction < 20 
    GROUP BY votes.object_id, votes.user_id, votes.content_type_id
    having COUNT(votes.object_id) > 1
    ) AS double_rows ON 
        double_rows.object_id = bad_rows.object_id 
        AND double_rows.user_id=bad_rows.user_id 
        AND bad_rows.is_archived=False
        AND double_rows.min_id <> bad_rows.id
    

    此选择有效,并为我提供要删除的行。现在,如果将select更改为delete,则查询将不起作用。

    DELETE bad_rows.*
    FROM votes as bad_rows
    INNER JOIN(
        SELECT  MIN(id) as min_id, votes.object_id, votes.user_id 
    FROM votes WHERE is_archived=FALSE AND 
         votes.direction < 20 
    GROUP BY votes.object_id, votes.user_id, votes.content_type_id
    having COUNT(votes.object_id) > 1
    ) AS double_rows ON 
        double_rows.object_id = bad_rows.object_id 
        AND double_rows.user_id=bad_rows.user_id 
        AND bad_rows.is_archived=False
        AND double_rows.min_id <> bad_rows.id
    

    第1行:删除错误的行*

    2 回复  |  直到 14 年前
        1
  •  3
  •   Andomar    14 年前

    不能指定要删除的列 * 在里面 bad_rows.* .)

    此外,大多数数据库不允许您指定要删除的别名。所以通常的删除方法如下:

    DELETE  VOTES
    WHERE   ID IN
            (
            <subquery selecting the ID's of the rows you want to delete>
            )
    
        2
  •  0
  •   Stephan    14 年前

    根据安多玛的建议,我成功了。

    DELETE FROM votes WHERE id IN (
    SELECT bad_rows.id
    FROM votes as bad_rows
    INNER JOIN(
    SELECT  MIN(id) as min_id, votes.object_id, votes.user_id 
    FROM votes where is_archived=FALSE and votes.direction < 20 
    
    GROUP BY votes.object_id, votes.user_id, votes.content_type_id
    having COUNT(votes.object_id) > 1
    ) as double_rows on double_rows.object_id = bad_rows.object_id and double_rows.user_id=bad_rows.user_id and bad_rows.is_archived=False
        and double_rows.min_id <> bad_rows.id
    )