简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM