gpt4 book ai didi

postgresql - 如何使用柴油进行 IN 查询?

转载 作者:行者123 更新时间:2023-12-05 01:57:33 25 4
gpt4 key购买 nike

我想用 diesel 做一个 IN 查询使用 PostgreSQL 13 从某些 id 集合中的歌曲表中选择歌曲集合。数据库执行的 SQL 可能是这样的:

select * from songs where id in(1,2,3)

我尝试使用像这样的使用rust 柴油方式做的事情:

pub fn songs(ids: Vec<i64>){
use schema::songs::dsl::*;
let connection = config::establish_connection();
let results = songs.filter(id.contains(ids))
.load::<QuerySongs>(&connection)
.expect("Error loading posts");
}

似乎没有用,当我使用 cargo build 编译项目代码时显示如下错误:

error[E0599]: the method `contains` exists for struct `songs::schema::songs::columns::id`, but its trait bounds were not satisfied
--> src/biz/music/songs.rs:37:35
|
37 | let results = songs.filter(id.contains(ids))
| ^^^^^^^^ method cannot be called on `songs::schema::songs::columns::id` due to unsatisfied trait bounds

我读了docssource code demo但它太短了,没有提到如何通过集合中的 id 执行查询。我应该怎么做才能在 rust diesel(diesel = { version = "1.4.4", features = ["postgres"] }) 中进行 IN 查询?这是一个最小的可复制 demo .

最佳答案

您正在寻找 .eq_any() .但请注意文档:

Creates a SQL IN statement.

Queries using this method will not be placed in the prepared statement cache. On PostgreSQL, you should use eq(any()) instead. This method may change in the future to automatically perform = ANY on PostgreSQL.

所以使用 .eq()any()您的代码应该类似于:

let results = songs.filter(id.eq(any(ids)))
.load::<QuerySongs>(&connection)
.expect("Error loading posts");

关于postgresql - 如何使用柴油进行 IN 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69139883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com