在这里,
有没有缩短这个MySQL查询?它需要根据它的价格规则从名为RuleValue的列中的PriceRuleDetail表中获取两个不同的行,但是使用别名,将它们返回到同一行。它在select语句中使用子查询,我认为是正确的,但可能有更简单的方法吗?
以下工作正常,我对此感到满意,但我想知道是否有办法让这个缩短???
SELECT Stock.*,
(SELECT PriceRuleDetail.RuleValue
FROM PriceRuleDetail
WHERE PriceRuleDetail.Sku = Stock.Sku
AND PriceRuleDetail.PriceRule = 'RG'
AND PriceRuleDetail.Quantity = 1) as Price,
(SELECT PriceRuleDetail.RuleValue
FROM PriceRuleDetail
WHERE PriceRuleDetail.Sku = Stock.Sku
AND PriceRuleDetail.PriceRule = 'RRP'
AND PriceRuleDetail.Quantity = 1) as WasPrice
FROM Stock, StockCategoryMemberList
WHERE StockCategoryMemberList.Sku = Stock.Sku
AND StockCategoryMemberList.CategoryCode = 'FIRE'
提前致谢。
安迪
答案 0 :(得分:6)
使用连接:
进行单个查询SELECT
Stock.*,
PRD1.RuleValue as Price,
PRD2.RuleValue as WasPrice
FROM
Stock,
StockCategoryMemberList,
PriceRuleDetail PRD1,
PriceRuleDetail PRD2
WHERE
StockCategoryMemberList.Sku = Stock.Sku
AND StockCategoryMemberList.CategoryCode = 'FIRE'
AND PRD1.Sku = Stock.Sku
AND PRD1.PriceRule = 'RG'
AND PRD1.Quantity = 1
AND
PRD2.Sku = Stock.Sku
AND PRD2.PriceRule = 'RRP'
AND PRD2.Quantity = 1
我做了同样的假设(对于一个股票记录,只有一个价格,只有一个WasPrice)。如果不是这样的话......查询将无法正常进行。也不是你的。
答案 1 :(得分:4)
您可以使用左连接来完成此操作
SELECT Stock.*,
PRD1.RuleValue as Price,
PRD2.RuleValue as WasPrice
FROM
Stock INNER JOIN
StockCategoryMemberList ON StockCategoryMemberList.Sku = Stock.Sku LEFT JOIN
PriceRuleDetail PRD1 ON PRD1.Sku = Stock.Sku
AND PRD1.PriceRule = 'RG'
AND PRD1.Quantity = 1 LEFT JOIN
PriceRuleDetail PRD2 ON PRD2.Sku = Stock.Sku
AND PRD2.PriceRule = 'RRP'
AND PRD2.Quantity = 1
WHERE StockCategoryMemberList.CategoryCode = 'FIRE'
答案 2 :(得分:2)
select s.*, prd1.rulevalue as price, prd2.rulevalue as wasprice
from
stock s
inner join stockcategorymemberlist scm
on s.sku = scm.sku
inner join priceruledetail prd1
on prd1.sku = s.sku and prd1.pricerule='RG' and prd1.quantity=1
inner join priceruledetail prd2
on prd2.sku = s.sku and prd2.pricerule='RRP' and prd2.quantity=1
where
s.categorycode='FIRE'
这也会更快,因为您不必为表中的每一行执行每个子选择。
答案 3 :(得分:0)
我建议实际上加长它而不是使用Stock。*,但是使用每个列名。当你使用*时,它必须查询表以获取列名,并且慢一点。