MySQL - 连接两个查询,第二个查询按第一个结果过滤

时间:2016-04-25 06:36:29

标签: mysql sql

我有一种情况,rearch将返回单个产品SKU,我将返回,例如:

SELECT 
pr.SKU,
pr.pkSKU,
pr.ColorDescription,
pr.CommonBrandName,
pr.BaseModel
FROM tbl_products AS pr WHERE pr.pkSKU = 160386  
ORDER BY pr.CommonBrandName, pr.SKU, pr.StandardColor 

但SKU可能有其他替代颜色可供选择,这些颜色通过BaseModel链接,我需要显示这些颜色,我知道我可以通过编写一个新的查询来做到这样:

SELECT 
pr.SKU,
pr.pkSKU,
pr.ColorDescription,
pr.CommonBrandName,
pr.BaseModel
FROM tbl_products AS pr WHERE pr.BaseModel = "result from previous query"  
ORDER BY pr.CommonBrandName, pr.SKU, pr.StandardColor

但我真正想做的是将其合并为一个查询,这可能吗?

其次,如果是,我需要订购结果,以便从第一个查询返回的SKU始终首先列出如下:

搜索SKU
替代颜色
搜索SKU
替代颜色 替代颜色
搜索SKU
替代颜色

1 个答案:

答案 0 :(得分:2)

可能是这样的

SELECT 
pr.SKU,
pr.pkSKU,
pr.ColorDescription,
pr.CommonBrandName,
pr.BaseModel
FROM tbl_products pr 
   INNER JOIN tbl_products pr1 ON pr.BaseModel = pr1.BaseModel
WHERE pr2.pkSKU = 160386  
ORDER BY 
   CASE WHEN pr.pkSKU = 160386 THEN 0 ELSE 1 END,
   pr.CommonBrandName, pr.SKU, pr.StandardColor