2

我有一个这样的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 条目(相同的值)。例如:

partnumbersafe   filtername   filtervalue

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

查询由 PHP 生成。我的 PHP 脚本中也有包含过滤数据的 POST 值(例如,品牌是丰田,型号是 F6)。

如何为过滤器名称/值对过滤这些结果?我更喜欢 sql 查询解决方案而不是 php 解决方案,在那里我可以查询 partnumbersafe,其中品牌是丰田,型号是 F6。这样它只会检索上表中的 partnumbersafe 123。

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

4

2 回答 2

2

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

SELECT partnumbersafe
FROM...
WHERE (filterName = 'Brand' AND filtervalue = 'toyota')
        OR
      (filterName = 'Model' AND filtervalue = 'F6')
GROUP BY partnumbersafe
HAVING COUNT(*) = 2
于 2012-10-25T14:41:07.670 回答
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

这假设您只需要 thepartnumbersafe 并且no filtername/ pair 将多次filtervalue应用于同一个。partnumbersafe

于 2012-10-25T14:41:40.117 回答