我有一个查询,我按照自己的意愿开始工作有点麻烦,查询看起来像这样:
SELECT
hf.file_path AS image,
hop.order_product_name AS product,
hop.order_product_price AS unit_flat_price,
.... <SHORTENED DOWN QUERY> ....
hc.currency_symbol AS currency,
ho.order_payment_method AS payment_method,
ho.order_created AS created
FROM
shop_order AS ho
LEFT JOIN
shop_order_product AS hop ON ho.order_id = hop.order_id
LEFT JOIN
shop_product AS hp ON hop.product_id = hp.product_id
LEFT JOIN
shop_file AS hf ON(
IF(
hp.product_parent_id > 0,
hp.product_parent_id,
hp.product_id
)
) = hf.file_ref_id
LEFT JOIN
shop_currency AS hc ON ho.order_currency_id = hc.currency_id
WHERE
ho.order_id = X AND(
hf.file_ordering = 0 OR hf.file_ordering = NULL
)
现在我的问题是,有时shop_file表在shop_file
表中没有匹配,然后我需要查询&#34;忽略&#34;加入,但是如果匹配,那么我需要它来应用AND
条款中的WHERE
部分我已经尝试了
WHERE
ho.order_id = X (
IF(
hf.file_path = NULL,
'',
AND(
hf.file_ordering = 0 OR hf.file_ordering = NULL
)
)
)
我尝试使用hf.file_path =
行的不同值,但没有任何帮助,我仍然遇到语法错误#1064 - You have an error in your .... syntax to use near '( IF(
我也试过
WHERE
ho.order_id = X AND(
hf.file_id = NULL OR(
hf.file_ordering = 0 OR hf.file_ordering = NULL
)
)
但这只是返回一个空的结果集(如果我删除整个AND( ... )
部分,我会得到我想要的结果。
现在我知道我可以按照
的方式做点什么WHERE
ho.order_id = X AND(
IF EXIST(SELECT file_path FROM ... )
但是这需要我在该查询中添加其他JOINS
以获得正确的结果(如果有图像)并且我想尝试避免必须添加JOIN&#39}如果可能WHERE ... AND( IF_EXIST (SELECT
。
答案 0 :(得分:1)
您需要将CASE添加到where语句中。
尝试这一点,将其添加到WHERE子句中:
AND CASE
WHEN hf.file_path IS NOT NULL
THEN hf.file_ordering = 0 OR hf.file_ordering IS NULL END;