java - 如何在 postgres 和 Hibernate/Spring 中使用 LIMIT 子句
问题描述
我有这个在我的 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
但也不起作用
解决方案
那是因为,据我正确理解文档,postgres 不支持使用LIMIT
indelete
语句。因此,您可以尝试使用解决方法来满足您的要求。例如,通过在 delete 语句中使用子查询来获取要删除的行。由于我不知道您的表格设计,我正在使用CTID
postgres 的此处来识别要删除的行。
取自文档(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);
推荐阅读
- reactjs - 在树数据结构上使用递归函数嵌套material-ui表,如何对齐列?
- pandas - 带有 int32 数组的 Pandas Dataframe 到 PySpark Dataframe 错误
- c++ - 为什么 gcc 'UNIX' 和 'unix' 宏不是一回事?
- javascript - 通过 setter 存储的新属性值在执行前生效
- javascript - click onclicking 是什么风格?
- mysql - 处理一对多和多对一映射的问题
- javascript - setTimeout 设置为 0 时延迟约 100 毫秒
- c++ - 在Arduino中为二维指针数组赋值
- javascript - HTML:在同一页面上自动显示给定的输入
- cron - 如何在 yaml 文件的 cron 中使用 0/10?