简体   繁体   English

如何在MySQL中将表与条件的结果字段联接

[英]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. 我有一个SQL查询,在我的SELECT部分中,有一个列是IF语句的结果。 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: 正如你所看到的“ final_vendor_id ”包含的值ioproductrel.vendorid除非它的值为null0 ,因为在这种情况下的价值products.vendor_id使用:

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. 我想基于此“ final_vendor_idfinal_vendor_id表,但是我只收到一个错误,即不存在具有该名称的字段。

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: 如果我再次在JOIN部分中写完整的IF语句,这似乎可以工作,但是我不确定它是否安全,我想知道是否有比这更简单的方法:

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' ... ON acc2.accountid ='final_vendor_id'

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

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