如何在 postgres 和 Hibernate/Spring 中使用 LIMIT 子句

How to use LIMIT clause with postgres and Hibernate/Spring

我的本机查询在我的 DAO 中不起作用

@Query(
            nativeQuery = true,
            value = "DELETE FROM products_in_carts WHERE cart_id =?1 AND product_name = ?2 LIMIT= 1"
    )
    void removeProduct(long id, String productName);

哪个returns:org.postgresql.util.PSQLException: ERROR: syntax error at or near "LIMIT"

我按照其他一些问题中的建议尝试了 OFFSET,但也不行

这是因为,据我正确理解文档,postgres 不支持在 delete 语句中使用 LIMIT。因此,您可以尝试使用变通方法来实现您的要求。例如,通过在 delete 语句中使用子查询来获取要删除的行。因为我不知道您的 table 设计,所以我在此处使用来自 postgres 的 CTID 来识别要删除的行。

摘自文档 (https://www.postgresql.org/docs/8.2/ddl-system-columns.html)

ctid The physical location of the row version within its table. Note that although the ctid can be used to locate the row version very quickly, a row's ctid will change each time it is updated or moved by VACUUM FULL. Therefore ctid is useless as a long-term row identifier. The OID, or even better a user-defined serial number, should be used to identify logical rows.

例如(未测试):

@Query(
        nativeQuery = true,
        value = "DELETE FROM products_in_carts WHERE ctid in (select ctid from product cart_id =?1 AND product_name = ?2 LIMIT= 1)"
)
void removeProduct(long id, String productName);

Postgres DELETE 语句不支持 LIMIT。

https://www.postgresql.org/docs/9.3/sql-delete.html

使用 where 来删除所需的行。