I have a nextJS project and I am using Prisma as an ORM.
The concerning database-tables look like this:
model cars_archive {
id Int @id @default(autoincrement())
...
inactivestamp DateTime? @db.DateTime(0)
@@index([brand], map: "brand")
@@index([model], map: "model")
}
model extras {
id Int @id @default(autoincrement()) @db.MediumInt
value String @unique(map: "value") @db.VarChar(255)
extras_cars extras_cars[]
}
model extras_cars {
car_id Int
extra_id Int @db.MediumInt
extras extras @relation(fields: [extra_id], references: [id], onUpdate: Restrict, map: "extras_cars_ibfk_1")
cars cars @relation(fields: [car_id], references: [id], onUpdate: Restrict, map: "extras_cars_ibfk_2")
@@id([car_id, extra_id])
@@index([car_id, extra_id], map: "car_id")
@@index([extra_id], map: "extra_id")
}
I need a query that fetches all cars that have certain extras. Something like this:
['Cruise Control', 'ABS',...]
To do that I created the following query-statement:
const cars = await prisma.cars.findMany({
where: {
extras_cars: {
every: {
extras: {
value: {
in: ['Cruise Control','ABS']
}
}
}
}
}
})
The thing is the query yields the desired result, but takes forever to return the list of cars (15 - 20 seconds).
I have tried the same thing with a simple SQL-Query which looks like this:
SELECT COUNT(*) FROM cars JOIN extras_cars ec on cars.id = ec.car_id JOIN extras e on e.id = ec.extra_id WHERE e.value='Cruise Control'
This query just takes about 1 second.
When looking at the debug-logs from Prisma it shows a really long SQL-query like this, which just doesn't make any sense to me:
SELECT COUNT(*) FROM (SELECT carsDB.cars.idFROMcarsDB.cars WHERE (carsDB.cars.id) NOT IN (SELECT t0.idFROMcarsDB.carsASt0INNER JOINcarsDB.extras_carsASj0 ON (j0.car_id) = (t0.id) WHERE ((NOT (j0.car_id,j0.extra_id) IN (SELECT t1.car_id, t1.extra_idFROMcarsDB.extras_carsASt1INNER JOINcarsDB.extrasASj1 ON (j1.id) = (t1.extra_id) WHERE (j1.value= ? ANDt1.car_idIS NOT NULL ANDt1.extra_idIS NOT NULL))) ANDt0.idIS NOT NULL)) /* traceparent=00-00-00-00 */) ASsub /* traceparent=00-00-00-00 */
Has somebody ever had a similar issue or has an idea of how to speed up the query?
The documentation of Prisma doesn't yield any useful information.
BTW: My database is a mariadb.
Thanks in advance.