Left join with multiple where clause for the first (left table)

I got this Query:

$query = mysql_query("SELECT arbejdsopgave.*, 
                     DATE_FORMAT(dato, '%d-%m-%Y') AS tid, 
                     tilfoejelser.*, 
                     DATE_FORMAT(datotf, '%d-%m-%Y') AS tid2
                     FROM arbejdsopgave LEFT JOIN tilfoejelser 
                     ON arbejdsopgave.sub_id=tilfoejelser.sub_id2 
                     WHERE arbejdsopgave.cat_id = '$id' 
                       AND datotf IS NULL 
                       OR datotf = (select max(datotf) 
                         FROM tilfoejelser 
                         WHERE arbejdsopgave.sub_id=tilfoejelser.sub_id2)
                         ORDER BY arbejdsopgave.sub_id")
                         or die(mysql_error());

I need to to only show rows from the table "arbejdsopgave" where arbejdsopgave.cat_id = '$id' but also where arbejdsopgave.status = 'closed'

I tried both in the join on and in the where.

First I get everything despite the extra where. Secondly I get only the rows where there are a join.

Can anyone help me - I am amazed that i even made it this far looking at my Query... Pls help

Upvotes: 0

Views: 47

Answers (1)

Daimos
Daimos

Reputation: 1473

This should work:

SELECT arbejdsopgave.*, DATE_FORMAT(dato, '%d-%m-%Y') AS tid, tilfoejelser.*, DATE_FORMAT(datotf, '%d-%m-%Y') AS tid2 
FROM arbejdsopgave 
LEFT JOIN tilfoejelser ON arbejdsopgave.sub_id=tilfoejelser.sub_id2
WHERE arbejdsopgave.cat_id = '$id' 
AND arbejdsopgave.status = 'closed'
AND (datotf IS NULL 
OR datotf = (
    select max(datotf) FROM tilfoejelser 
    WHERE arbejdsopgave.sub_id=tilfoejelser.sub_id2) )
ORDER BY arbejdsopgave.sub_id

I suppose you forget about () around datotf OR condition

Upvotes: 1

Related Questions