我正在尝试实现该count_distinct_labels
函数以使用 Diesel 和 PostgreSQL 计算一列数组中的不同元素。
例如,我有一个这样的表:
------------------
| labels |
------------------
| ['foo', 'bar'] |
------------------
| ['bar', 'baz'] |
------------------
在这种情况下,count_distinct_labels()
应该是3
,因为有 3 个唯一标签 ( 'foo', 'bar', 'baz'
)。
我发现下面的 SQL 返回了想要的结果,但我不知道如何将它翻译成 Diesel 表达式。
SELECT COUNT(*) FROM (SELECT DISTINCT unnest(labels) FROM t) AS label;
这是我的源代码:
#[macro_use]
extern crate diesel;
extern crate dotenv;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenv::dotenv;
use std::env;
mod schema {
table! {
t (id) {
id -> Int4,
labels -> Array<Text>,
}
}
#[derive(Insertable)]
#[table_name = "t"]
pub struct NewRow<'a> {
pub labels: &'a [String],
}
}
fn count_distinct_labels(conn: &PgConnection) -> i64 {
// SELECT COUNT(*) FROM (SELECT DISTINCT unnest(labels) FROM t) AS label
unimplemented!()
}
fn main() {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let conn = PgConnection::establish(&database_url)
.expect(&format!("Error connecting to {}", database_url));
diesel::insert_into(schema::t::dsl::t)
.values(&vec![
schema::NewRow {
labels: &["foo".to_string(), "bar".to_string()],
},
schema::NewRow {
labels: &["bar".to_string(), "baz".to_string()],
},
]).execute(&conn)
.unwrap();
// how to implement?
assert_eq!(count_distinct_labels(&conn), 3);
}
和 Cargo.toml:
[package]
name = "how-to-count-distinct"
version = "0.1.0"
authors = ["name"]
[dependencies]
diesel = { version = "1.0", features = ["postgres"] }
dotenv = "0.13"
我还创建了一个包含完整示例的存储库。如果要复制,请克隆此 repo 和cargo run
. 请注意,您必须在运行代码之前启动 Postgres 服务。