【问题标题】:How to use LIMIT clause with postgres and Hibernate/Spring如何在 postgres 和 Hibernate/Spring 中使用 LIMIT 子句
【发布时间】:2021-01-25 10:50:22
【问题描述】:

我的本​​机查询在我的 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);

返回:org.postgresql.util.PSQLException: ERROR: syntax error at or near "LIMIT"

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

【问题讨论】:

    标签: java spring hibernate spring-data-jpa spring-rest


    【解决方案1】:

    这是因为,正如我对文档的正确理解,postgres 不支持在 delete 语句中使用 LIMIT。因此,您可以尝试使用解决方法来满足您的要求。例如,通过在 delete 语句中使用子查询来获取要删除的行。由于我不知道您的表格设计,因此我在此处使用 postgres 中的 CTID 来识别要删除的行。

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

    ctid 行版本在其表中的物理位置。请注意,尽管 ctid 可用于非常快速地定位行版本,但行的 ctid 会在每次被 VACUUM FULL 更新或移动时发生变化。因此 ctid 作为长期行标识符是无用的。应该使用 OID,甚至更好的是用户定义的序列号来识别逻辑行。

    例如(未测试):

    @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);
    

    【讨论】:

      【解决方案2】:

      Postgres DELETE 语句不支持 LIMIT。

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

      使用 where 来删除所需的行。

      【讨论】:

        猜你喜欢
        • 2018-07-02
        • 1970-01-01
        • 2011-02-18
        • 2022-01-12
        相关资源
        最近更新 更多