我有一个由以下列组成的表:
id name value
serial text text
我需要移除id
值最小且name = 'SUPPORT_EMAIL'
的行。我怎样才能以最佳方式做到这一点?我试过了:
DELETE FROM propertie
WHERE name = 'SUPPORT_EMAIL'
HAVING id = MIN(id)
GROUP BY name ;
和
DELETE FROM propertie
WHERE name = 'SUPPORT_EMAIL'
GROUP BY name
HAVING id = MIN(id) ;
但它没有用。当然,我可以写
DELETE FROM propertie
WHERE id = (SELECT id
FROM propertie
WHERE name = 'SUPPORT_EMAIL' and id = (SELECT MIN(id)
FROM propertie
WHERE name = 'SUPPORT_EMAIL')
)
但对我来说似乎很奇怪。
答案 0 :(得分:1)
你在那里非常接近,但可以通过以下方式简化你的工作:
DELETE FROM propertie
WHERE id = (SELECT MIN(id)
FROM propertie
WHERE name = 'SUPPORT_EMAIL')
你也可以:
DELETE FROM propertie
WHERE id = (SELECT id
FROM propertie
WHERE name = 'SUPPORT_EMAIL'
ORDER BY id
LIMIT 1)
我不确定这是否是合法的PostgreSQL语法:
DELETE FROM propertie
WHERE name = 'SUPPORT_EMAIL'
ORDER BY id
LIMIT 1
答案 1 :(得分:1)
为了在删除查询中使用聚合函数,我们需要使用如下的子查询。我觉得这是优化的方式:
DELETE FROM attendence
WHERE
id IN
(select min(id) from attendence where name = 'SUPPORT_EMAIL' );
答案 2 :(得分:1)
您的问题不清楚,但是如果有多个重复行,并且您想要删除所有重复但最后一个(ID最高的那个),您可以使用此查询:
DELETE FROM propertie p1
USING propertie p2
WHERE
p1.name=p2.name
AND p1.id<p2.id;
或者如果你想删除重复的SUPPORT_EMAILs:
DELETE FROM propertie p1
USING propertie p2
WHERE
p1.name='SUPPORT_EMAIL'
AND p1.name=p2.name
AND p1.id<p2.id;
请参阅示例小提琴here。