2

我有一个查询,我试图从 SQL 转换为 rust/diesel,但在使用柴油创建子查询时遇到了问题。

我正在使用柴油 =“1.4.2”以及 postgres 功能。

我有以下架构和模型......

#[macro_use]
extern crate diesel;

mod schema {
    table! {
        jobs (id) {
            id -> Int4,
        }

        appointments (id) {
            id -> Int4,
        }

        categories (id) {
            id -> Int4
        }

        appointments_categories(appointment_id, category_id) {
            appointment_id -> Int4,
            category_id -> Int4
        }
    }
}

mod models {
    #[derive(Debug, Identifiable)]
    pub struct Job {
        pub id: i32,
    }

    #[derive(Debug, Identifiable)]
    pub struct Appointment {
        pub id: i32,
    }

    #[derive(Debug, Identifiable)]
    pub struct Category {
        pub id: i32,
    }

    #[derive(Debug, Identifiable)]
    #[primary_key(appointment_id, appointment_type_id)]
    pub struct AppointmentCategory {
        pub id: i32,
    }
}

fn main() {}

然后我有这个 SQL 查询:

DELETE FROM appointments_categories
WHERE ROW ("appointment_id", "category_id")
    IN (
        SELECT
            appointment.id AS appointment_id, appointments_categories. "category_id" FROM appointment
        INNER JOIN appointments_categories ON appointments_categories. "appointment_id" = appointment.id
            WHERE appointment."job_id" = 125
            LIMIT 10000);

到目前为止,我尝试使用以下方法,但无法弄清楚如何绑定子查询/表达式。

let sub_query = appointment_dsl::appointment
    .inner_join(appt_cat_dsl::appointments_categories)
    .filter(appointment_dsl::job_id.eq(job_id))
    .select((appointment_dsl::id, appt_cat_dsl::category_id));

let rows_deleted = delete(appt_cat_dsl::appointments_categories
    .filter(sql(format!("ROW(appointmentId, appointmentTypeId) IN {}", subquery))))?;

我知道还有其他方法可以编写删除查询,但我需要能够限制它删除的行数。关联/联结表很大,每个作业有 300 万行,作业每 15 分钟运行一次。一次删除它会锁定数据库,所以它不是一个选项。

抱歉,我无法在生锈的操场上制作可重现的样品,因为它没有柴油。

4

0 回答 0