使用Postgres数据库中的Diesel从带有子查询的关联表中删除

时间:2019-07-13 20:00:11

标签: postgresql rust rust-diesel

我有一个查询,我试图将其从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分钟运行一次。一次删除所有内容将锁定数据库,因此这不是一个选择。

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

0 个答案:

没有答案