我正在构建一个连接多个表的查询,一个表prodRecipe
将包含某些行的数据,但不是全部,但tmp_inv1
将包含所有内容的计数信息。问题是,tmp_inv1.count
取决于项目是否在prodRecipe
表中。
即。如果存在prodRecipe.product
,则tmp_inv1.count
基于此,否则它基于product.prodID
。
在JOIN中使用OR似乎可以根据任何给出有效结果的方式进行填充,但是我想知道这是否会导致我不知道的不必要或灾难性的结果?
- 我一时兴起尝试使用OR,因为我还没有找到更好的解决方案。但最重要的是它对PHP很友好,所以我不能使用多个或嵌套的选择查询.--
SELECT invTrack AS track, varID, varSKU, revelSku, revelInvID, p.prodID AS prodID, pr.ingredient AS ing, pr.main_product AS mainProduct, pr.product AS product, i.invID AS invC, i.count, pr.qty AS Xply
FROM shopifyProd sp
LEFT JOIN product p ON sp.revelSku = p.sku AND p.location = 1
LEFT JOIN prodRecipe pr ON p.prodID = pr.main_product
LEFT JOIN tmp_inv1 i ON pr.product = i.prodID OR p.prodID = i.prodID
WHERE 1
答案 0 :(得分:0)
要避免多次匹配,您需要加入两次(每个条件一次)并选择优先级匹配。
SELECT invTrack AS track, varID, varSKU, revelSku, revelInvID, p.prodID AS prodID, pr.ingredient AS ing, pr.main_product AS mainProduct, pr.product AS product
, CASE WHEN p_i.prodID IS NOT NULL THEN p_i.invID ELSE pr_i.invID END AS invC
, CASE WHEN p_i.prodID IS NOT NULL THEN p_i.count ELSE pr_i.count END AS `count`
, pr.qty AS Xply
FROM shopifyProd sp
LEFT JOIN product p ON sp.revelSku = p.sku AND p.location = 1
LEFT JOIN prodRecipe pr ON p.prodID = pr.main_product
LEFT JOIN tmp_inv1 p_i ON p.product = p_i.prodID
LEFT JOIN tmp_inv1 pr_i ON pr.product = pr_i.prodID
WHERE 1