我正在尝试实现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"
我还创建了a repo containing the full example。如果要复制,请克隆此repo和
cargo run
。请注意,您必须在运行代码之前启动Postgres服务。 最佳答案
新增检视
从Diesel 1.31开始,最简单的操作是向数据库添加 View :
CREATE VIEW unique_labels AS (SELECT DISTINCT unnest(labels) FROM t);
然后,您可以将有关 View 的信息告诉Diesel:
table! {
unique_labels (unnest) {
unnest -> Text,
}
}
并直接查询:
fn count_distinct_labels(conn: &PgConnection) -> i64 {
use schema::unique_labels::dsl::*;
use diesel::dsl;
unique_labels.select(dsl::count_star()).first(conn).unwrap()
}
使用
sql_query
您总是可以退回到直接执行SQL的“大锤子”:
fn count_distinct_labels(conn: &PgConnection) -> i64 {
use diesel::sql_types::BigInt;
#[derive(QueryableByName)]
struct Count {
#[sql_type = "BigInt"]
count: i64,
}
diesel::sql_query(r#"SELECT COUNT(*) FROM (SELECT DISTINCT unnest(labels) FROM t) AS label"#)
.load::<Count>(conn)
.expect("Query failed")
.pop()
.expect("No rows")
.count
}
1 Diesel 1.3不能手动传递自己的
FROM
子句,也许还有其他限制。关于sql - 如何使用Diesel计算数组列中不同元素的数量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51852226/