如何从复杂的SQL查询中筛选结果?

时间:2012-10-25 14:34:25

标签: php sql subquery filtering

我有一个像这样的SQL查询:

SELECT  `categories`.`partnumbersafe`, `filters`.`filtername`,  `filters`.`filtervalue` 
FROM  `products_categories` AS  `categories` 
LEFT OUTER JOIN  `products` AS  `product` ON  `categories`.`partnumbersafe` =  `product`.`partnumbersafe` 
LEFT OUTER JOIN  `products_filters` AS  `filters` ON  `categories`.`partnumbersafe` =  `filters`.`partnumbersafe` 
WHERE  `categories`.`categoryid` =4
AND (`product`.`visibility` =1 OR  `product`.`visibility` =2)
AND  `product`.`status` =1

这给了我一个结果,其中有多个partnumbersafe条目(相同的值)具有不同的filternames和filtervalues。例如:

partnumbersafe   filtername   filtervalue

123                brand        toyota
123                model        F5
123                type         business
678                brand        toyota
678                model        F6

查询由PHP生成。我的PHP脚本中也有POST值,它包含filterdata(品牌是丰田,模型是F6)。

如何针对filtername / value对过滤这些结果?我更喜欢一个sql查询解决方案而不是一个php解决方案,在那里我可以查询partnumbersafe,其中品牌是丰田,模型是F6。因此,它只会检索上表中的partnumbersafe 123。

表products_filters包含上表表格所示的所有数据。

2 个答案:

答案 0 :(得分:2)

你需要在这里有多个条件。每个partnumbersafe的记录数等于您提供的条件数。

SELECT partnumbersafe
FROM...
WHERE (filterName = 'Brand' AND filtervalue = 'toyota')
        OR
      (filterName = 'Model' AND filtervalue = 'F6')
GROUP BY partnumbersafe
HAVING COUNT(*) = 2

答案 1 :(得分:1)

SELECT
  `categories`.`partnumbersafe`
FROM
  `products_categories` AS  `categories` 
LEFT OUTER JOIN
  `products`            AS  `product`
    ON  `categories`.`partnumbersafe` = `product`.`partnumbersafe` 
LEFT OUTER JOIN
  `products_filters`    AS  `filters`
    ON  `categories`.`partnumbersafe` = `filters`.`partnumbersafe` 
WHERE
     `categories`.`categoryid` = 4
AND (`product`.`visibility` =1 OR  `product`.`visibility` =2)
AND  `product`.`status` =1
AND
(
  (`filters`.`filtername` = 'Brand' AND `filters`.`filtervalue` = 'Toyota')
  OR
  (`filters`.`filtername` = 'Model' AND `filters`.`filtervalue` = 'F6')
)
GROUP BY
  `categories`.`partnumbersafe`
HAVING
  COUNT(*) = 2

这假设您只需要partnumbersafe filtername / filtervalue对不会适用于同一对partnumbersafe不止一次。