如果条件为true,则按条件加入查询

时间:2019-06-20 14:08:44

标签: mysql

我是SQL的新手,我想在Join中了解一些带有条件的查询。我的问题是我需要检查一些条件,如果使用左连接使用该ID是真实的,如果使用另一个ID并使用false则是false桌子


select 
 coalesce(supplier.NAME,PARTY2_supplier,PARTY1_supplier)  as Supplier,
     from ACCOUNT acc
     left join RELATIONSHIP r on r.RELATIONSHIP_ID = 2
     left join ORGANIZATION supplier on supplier.ORGANIZATION_ID = acc.SUPPLIER_ID 

if (r.name = 'sales' or r.name = 'purchase'){

        left join ORGANIZATION PARTY2_supplier on PARTY2_supplier.ORGANIZATION_ID = r.PARTY2_ID

}
else {

        left join ORGANIZATION PARTY1_supplier on PARTY1_supplier.ORGANIZATION_ID = r.PARTY1_ID

}
        where acc.ACCOUNT_ID = 34;

我需要一个具有该帐户ID的正确供应商名称

2 个答案:

答案 0 :(得分:0)

快速答案是:您必须联接所有表并使用if函数。

if函数的工作方式如下:
它将为下一次查询yes返回select if(500 < 1000, "yes", "no");

因此,借助此知识,您可以执行以下操作:

select
if (r.name = 'sales' or r.name = 'purchase', PARTY2_supplier.NAME, PARTY1_supplier.NAME) as Supplier
from ACCOUNT acc
left join RELATIONSHIP r on r.RELATIONSHIP_ID = 2
left join ORGANIZATION supplier on supplier.ORGANIZATION_ID = acc.SUPPLIER_ID 
left join ORGANIZATION PARTY1_supplier on PARTY1_supplier.ORGANIZATION_ID = r.PARTY1_ID
left join ORGANIZATION PARTY2_supplier on PARTY2_supplier.ORGANIZATION_ID = r.PARTY2_ID
where acc.ACCOUNT_ID = 34
;

答案 1 :(得分:0)

但是我得到一个答案,我们可以直接检查情况

select 
 supplier.NAME  as name,
     from ACCOUNT acc
     left join RELATIONSHIP r on r.RELATIONSHIP_ID = 2
     left join ORGANIZATION supplier on supplier.ORGANIZATION_ID = coalesce(supplier.NAME, if(r.name = 'sales' or r.name = 'purchase', party1.Id, party2.Id) )

        where acc.ACCOUNT_ID = 34;