0

我有这个查询,但我只想加入PostageRulesPostageGroups如果p.delivery值为 -1

澄清一下,我只想要一个交付值,如果p.delivery是 -1,那么我们需要从表中获取po.delivery值。PostageRules目前查询得到的po.delivery值不管p.delivery

这可以在单个查询中实现吗?

SELECT  
   p.id as prod_id, p.delivery as delivery, 
   po.delivery AS delivery 
FROM 
   products AS p 
LEFT JOIN 
   PostageRules AS po ON p.shopkeeper = po.shopkeeper
LEFT JOIN 
   PostageGroups  AS pg ON po.groupID = pg.id
        AND po.minQty <= 1
        AND po.maxQty >= 1
        AND po.minPrice <= p.Price
        AND po.maxPrice >= p.Price
        AND po.minWeight <= p.weight
        AND po.maxWeight >= p.weight                
WHERE 
    (p.id = '32323') 
ORDER BY 
    po.preference   
4

2 回答 2

2
SELECT  p.id as prod_id, ISNULL(po.delivery, p.delivery) AS delivery 
    FROM products AS p 
    LEFT JOIN PostageRules AS po ON p.shopkeeper = po.shopkeeper and p.delivery = -1
    LEFT JOIN PostageGroups  AS pg ON po.groupID = pg.id and p.delivery = -1
    AND po.minQty <= 1
    AND po.maxQty >= 1
    AND po.minPrice <= p.Price
    AND po.maxPrice >= p.Price
    AND po.minWeight <= p.weight
    AND po.maxWeight >= p.weight                
    WHERE (p.id = '32323') ORDER BY po.preference   
于 2012-10-04T13:20:35.517 回答
0

试试这个:

SELECT  p.id as prod_id, p.delivery as delivery, CASE WHEN p.delivery=-1 then po.delivery else null end AS delivery 
        FROM products AS p 
        LEFT JOIN PostageRules AS po ON p.shopkeeper = po.shopkeeper
        LEFT JOIN PostageGroups  AS pg ON po.groupID = pg.id
        AND po.minQty <= 1
        AND po.maxQty >= 1
        AND po.minPrice <= p.Price
        AND po.maxPrice >= p.Price
        AND po.minWeight <= p.weight
        AND po.maxWeight >= p.weight                
        WHERE (p.id = '32323') ORDER BY po.preference   
于 2012-10-04T13:18:55.140 回答