简体   繁体   中英

How to join a table with a result field of a condition in MySQL

I have an SQL query where in my SELECT part I have a column which is a result of an IF statement. As you can see ' final_vendor_id ' contains the value of ioproductrel.vendorid except when it's value is null or 0 , because in this case the value of products.vendor_id is used:

SELECT 
    IF(ioproductrel.vendorid IS NULL OR ioproductrel.vendorid = 0, products.vendor_id, ioproductrel.vendorid) AS 'final_vendor_id',
    account.accountname AS 'account',
    salesorder.duedate
FROM 
    internalorder LEFT JOIN ioproductrel ON internalorder.internalorderid = ioproductrel.internalorderid
    LEFT JOIN products ON ioproductrel.productid = products.productid 
    LEFT JOIN slip_relations ON internalorder.internalorderid = slip_relations.child_crmid
    INNER JOIN salesorder ON slip_relations.parent_crmid = salesorder.salesorderid
    LEFT JOIN account ON salesorder.accountid = account.accountid
    LEFT JOIN account AS acc2 ON acc2.accountid = final_vendor_id
WHERE 
    internalorder.internalorderid = 8982

I want to join a table based on this ' final_vendor_id ', but I just get an error that no field with such a name exists.

If I write the whole IF statement in the JOIN part again, it seems to work but Im not sure if it is safe and Im wondering if is there any simplier way than this:

SELECT 
    IF(ioproductrel.vendorid IS NULL OR ioproductrel.vendorid = 0, products.vendor_id, ioproductrel.vendorid) AS 'final_vendor_id',
    account.accountname AS 'account',
    salesorder.duedate
FROM 
    internalorder LEFT JOIN ioproductrel ON internalorder.internalorderid = ioproductrel.internalorderid
    LEFT JOIN products ON ioproductrel.productid = products.productid 
    LEFT JOIN slip_relations ON internalorder.internalorderid = slip_relations.child_crmid
    INNER JOIN salesorder ON slip_relations.parent_crmid = salesorder.salesorderid
    LEFT JOIN account ON salesorder.accountid = account.accountid
    LEFT JOIN account AS acc2 ON acc2.accountid = IF(ioproductrel.vendorid IS NULL OR ioproductrel.vendorid = 0, products.vendor_id, ioproductrel.vendorid)
WHERE 
    internalorder.internalorderid = 8982

What if set single quotes in left join section like:
...ON acc2.accountid = 'final_vendor_id'

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