通过在PG 9.1上使用libpq,我试图编写查询以从具有最高索引'my_id'的行获取值:
SELECT my_id, col2, col3
FROM mytable
WHERE my_id = MAX(my_id)
这给了我错误:
错误:WHERE子句中不允许聚合...
如何正确编写此类查询?
答案 0 :(得分:30)
如果您的目标是获取具有最高my_id值的行,则以下查询应实现相同的目标。
SELECT my_id, col2, col3
FROM mytable
ORDER BY my_id DESC
LIMIT 1
答案 1 :(得分:8)
只需按my_id
排序,只使用limit 1
SELECT my_id, col2, col3
FROM mytable
order by my_id desc
limit 1
另一种性能较差的方式是
SELECT my_id, col2, col3
FROM mytable
where my_id = (select max(my_id) from mytable)
答案 2 :(得分:5)
子查询可以帮助您
SELECT my_id, col2, col3 FROM mytable WHERE my_id = (select MAX(my_id) FROM mytable)
答案 3 :(得分:2)
SELECT my_id, col2, col3 FROM mytable WHERE my_id = (select MAX(my_id) FROM mytab)
或使用
SELECT my_id, col2, col3 FROM mytable ORDER BY my_id DESC LIMIT 1
答案 4 :(得分:0)
当my_id上有索引时,带有子查询的索引应该更快。当你没有索引时,请选择“order by”。 (如果相关,则obv。取决于数据库大小)