简体   繁体   中英

Left Join query with flag condition

Hy, i have problems for show all the rows of a table cash , im trying to get the cashassignment_id column if the column doesn't have data then print Unallocated as result. But the Cash 1 is Missing.

My sql:

SELECT  
    cash.cash_id,
    cash.cash_name,
    IFNULL(cash_assignments.cashassignment_id, 'Unallocated') AS cashassignment_id
FROM cash
    LEFT JOIN cash_assignments USING(cash_id)
WHERE cash_assignments.cashassignment_valid = TRUE OR cash_assignments.cashassignment_valid IS NULL

Demo Link http://sqlfiddle.com/#!9/ce446/1/0

Try moving the where condition to the on clause:

SELECT c.cash_id, c.cash_name,
       COALESCE(ca.cashassignment_id, 'Unallocated') AS cashassignment_id
FROM cash c LEFT JOIN
     cash_assignments ca
     ON c.cash_id = ca.cash_id AND ca.cashassignment_valid = TRUE ;

I also modified the query to use table aliases (easier to write and read the query) and to use COALESCE() instead of ISNULL() ( COALESCE() is ANSI standard).

Your query is filtering the results after the join happened, so you will filter out stuff you wanna keep. (if I understood right)

Instead you can always do subqueries:

SELECT K.X, L.Y FROM
    (SELECT X FROM A) AS K
LEFT JOIN
    (SELECT Y FROM B) AS L
USING (SOME_ID)

and in the subqueries you can add your where clause:

    (SELECT Y FROM B WHERE SOMECOND) AS L

This way you can filter out the lines you need before joining the tables.

Applying this to your problem is trivial and left as excercise for the interested reader. :)

Usually you don't need to filter the rows in the subquery, the optmizer will do that, this would be enough for the left side, (or without placeholder just A):

    A AS K

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