I have a query which checks if someone already filled in something in another table. It checks first if it is IN the table, and secondly after the UNION it checks if it is NOT in the table..
I built this query together with someone who knows a lot more about SQL then me. Now i'm wondering if this can be shortened?
I was thinking maybe with an CASE WHEN .. THEN 0 ELSE 1 in stead of checking with 2 queries and doing the union
SELECT
l.id,
l.naam,
r.id as revisie,
r.beschrijving as revisiebeschrijving,
"DONE"
FROM lijsten l
JOIN revisies r ON r.lijst_id = l.id
JOIN werknemerlijsten wl ON wl.lijst_id = l.id
WHERE
wl.werknemer_id = :id AND r.actief = 1
AND r.id IN
(
SELECT
r2.id
FROM revisies r2
JOIN antwoorden a ON a.revisie_id = r2.id
WHERE a.werknemer_id = wl.werknemer_id
)
UNION
SELECT
l.id,
l.naam,
r.id as revisie,
r.beschrijving as revisiebeschrijving,
"NOT DONE"
FROM lijsten l
JOIN revisies r ON r.lijst_id = l.id
JOIN werknemerlijsten wl ON wl.lijst_id = l.id
WHERE
wl.werknemer_id = :id AND r.actief = 1
AND r.id NOT IN
(
SELECT
r2.id
FROM revisies r2
JOIN antwoorden a ON a.revisie_id = r2.id
WHERE a.werknemer_id = wl.werknemer_id
)
Final Solution
this is the final solution, And the ORDER BY works in this version, without subquerys
SELECT l.id
, l.naam
, r.id as revisie
, r.beschrijving as revisiebeschrijving
, CASE WHEN a.werknemer_id IS NULL
THEN 0
ELSE 1 END AS ingevuld
FROM werknemerlijsten AS wl
INNER
JOIN lijsten AS l
ON l.id = wl.lijst_id
INNER
JOIN revisies AS r
ON r.lijst_id = l.id
AND r.actief = 1
LEFT OUTER
JOIN antwoorden AS a
ON a.revisie_id = r.id
AND a.werknemer_id = wl.werknemer_id
WHERE wl.werknemer_id = :id
ORDER BY ingevuld