SQL中的互斥值

Qui*_*nVK 2 mysql sql

我有一个查询从表中选择产品.产品可以有多种价格(考虑各种价格)和默认价格.

当然,这是一对多的关系.我需要选择具有给定价格或默认价格的产品 - 这意味着相互排斥.我知道这可以通过单独的查询和WHERE(非)IN子句或union语句来完成,但我确信必须有一种更优化的方式.我的查询目前看起来像这样:

SELECT products.*, products_prices.price 
FROM products RIGHT JOIN 
     products_prices ON (products.id = products_prices.productId) 
WHERE products_prices.businessId = ? 
OR    products_prices.businessId IS NULL // this needs to become mutual.
Run Code Online (Sandbox Code Playgroud)

编辑:我最终使用了这个查询,这是Gordon Linoff的略微修改版本:

 SELECT distinct p.*, coalesce(pp.price, defpp.price)
 FROM products p LEFT JOIN 
      products_prices pp
      ON p.id = pp.productId and pp.businessId = ? left join
      products_prices defpp
      on p.id = defpp.productId and defpp.businessId is NULL
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 7

如果我正确理解您的问题,products表格将具有默认价格,product_prices表格将有任何其他价格.

您想知道默认价格的使用位置,这意味着没有其他价格.为此,请使用left outer join:

SELECT p.*, coalesce(pp.price, p.default_price)
FROM products p LEFT OUTER JOIN 
     products_prices pp
     ON p.id = pp.productId
WHERE pp.price = GIVENPRICE or pp.price is null
Run Code Online (Sandbox Code Playgroud)

根据您的注释,您将默认价格存储在业务ID为NULL的记录中.在这种情况下,我会对价格表进行两次连接:

SELECT p.*, coalesce(pp.price, defpp.price)
FROM products p LEFT OUTER JOIN 
     products_prices pp
     ON p.id = pp.productId and pp.price = GIVENPRICE left outer join
     products_prices defpp
     on p.id = defpp.productId and defpp.businessId is NULL
Run Code Online (Sandbox Code Playgroud)

第一次加入获得与给定价格匹配的价格.第二个获得默认价格.如果存在,则使用第一个结果,否则使用第二个结果.