简体   繁体   English

带标志条件的左联接查询

[英]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. 嗨,我在显示表cash所有行时遇到问题,如果该列没有数据,则尝试获取cashassignment_id列,然后将结果打印为Unallocated But the Cash 1 is Missing. 但是Cash 1丢失了。

My sql: 我的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 演示链接http://sqlfiddle.com/#!9/ce446/1/0

Try moving the where condition to the on clause: 尝试将where条件移动到on子句:

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). 我还修改了查询以使用表别名(更易于编写和读取查询),并使用COALESCE()代替ISNULL()COALESCE()是ANSI标准)。

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: 在子查询中,您可以添加where子句:

    (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):

    A AS K

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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