SQL ISNULL但如果不存在则还需要结果

时间:2015-03-27 15:15:39

标签: sql

我试图编写一个查询来从我的数据库中导出订单。到目前为止,我可以得到它来拉取记录,如果在' extrafields'中的一个字段。是空的或有内容但我无法弄清楚如果在' extrafields'中没有数据也包括在内?数据库如果有人能提供任何帮助,我将非常感激,这就是我迄今所拥有的。

    SELECT 
    CASE WHEN ISNULL(e.content) THEN ol.code ELSE CONCAT(ol.code, ' ** ', e.content) END as `ItemNumber`,
CASE WHEN ISNULL(e.content) THEN ol.name ELSE CONCAT(ol.name, ' ** ', e.content) END as `ItemTitle`,
o.orderID AS orderId,
ol.productID AS orderItemId,
ol.qty AS Quantity,
ol.price + ol.taxamount AS CostPerUnit,  
'' AS ProductOption,
0 AS ItemTaxRate,
0 AS DiscountPercent,
ol.lineID
FROM
`jss_orders_headers` o,
`jss_orders_lines` ol

LEFT JOIN jss_orders_extrafields e ON e.lineID = ol.lineID
WHERE
e.content!=" " 
and ol.orderID = o.orderID 
AND e.extraFieldID NOT IN (130, 114, 113, 111, 84, 81)
and e.exValID > 0

1 个答案:

答案 0 :(得分:3)

当您在WHERE子句中引用左连接列(在您的案例中来自jss_orders_extrafields的列)时,您强制连接的行为就像它是INNER连接一样。相反,将这些测试作为连接条件的一部分。

...
LEFT JOIN jss_orders_extrafields e 
    ON e.lineID = ol.lineID
        AND e.content != ' '
        AND e.extreaFieldID NOT IN (130, 114, 113, 111, 84, 81)
        AND e.exValID > 0
...

此外,在您的联接风格中保持一致,不要混合隐式和显式联接。

...
FROM `jss_orders_headers` o
    INNER JOIN `jss_orders_lines` ol
        ON o.orderID = ol.orderID
...

并从WHERE子句中删除o.orderID = ol.orderID测试。

所以,把它们放在一起:

SELECT CASE WHEN ISNULL(e.content) THEN ol.code ELSE CONCAT(ol.code, ' ** ', e.content) END as `ItemNumber`,
       CASE WHEN ISNULL(e.content) THEN ol.name ELSE CONCAT(ol.name, ' ** ', e.content) END as `ItemTitle`,
       o.orderID AS orderId,
       ol.productID AS orderItemId,
       ol.qty AS Quantity,
       ol.price + ol.taxamount AS CostPerUnit,  
       '' AS ProductOption,
       0 AS ItemTaxRate,
       0 AS DiscountPercent,
       ol.lineID
    FROM `jss_orders_headers` o
        INNER JOIN `jss_orders_lines` ol
            ON o.orderID = ol.orderID   
        LEFT JOIN jss_orders_extrafields e 
            ON e.lineID = ol.lineID
                AND e.content!=" " 
                AND e.extraFieldID NOT IN (130, 114, 113, 111, 84, 81)
                AND e.exValID > 0;