SQL Server选择查询 - 条件JOIN

时间:2012-10-04 13:15:16

标签: sql-server select

我有此查询,但如果PostageRules的值为-1,我只想加入PostageGroupsp.delivery

为了澄清,我只需要一个交付值,如果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   

2 个答案:

答案 0 :(得分: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   

答案 1 :(得分: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