我有一个SQL查询,在SELECT
部分我有一个列是IF语句的结果。正如您所看到的,“final_vendor_id
”包含ioproductrel.vendorid
的值,除非它的值为null
或0
,因为在这种情况下,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
我想基于这个'final_vendor_id
'加入一个表,但是我得到一个错误,即不存在具有这种名称的字段。
如果我再次在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
答案 0 :(得分:0)
如果在左连接部分设置单引号,如下所示: ...... ON acc2.accountid ='final_vendor_id'