MYSQL按属性过滤产品

时间:2013-04-09 10:57:09

标签: mysql attributes product

如何选择具有用户指定的所有属性的产品

例如:用户指定搜索产品的属性:41,2,4,6

MYSQL结构是:

表:报价

`id` int(11) NOT NULL auto_increment,

`title_pl` varchar(100) character set utf8 collate utf8_polish_ci NOT NULL,

表:offer_att

`id` int(11) NOT NULL auto_increment,
`offer_id` int(11) NOT NULL,
`att_id` int(11) NOT NULL,

TABLE att

`id` int(11) NOT NULL auto_increment,

`title_pl` varchar(255) character set utf8 collate utf8_polish_ci NOT NULL,

2 个答案:

答案 0 :(得分:0)

这是你需要的吗?

SELECT *
FROM offer
WHERE id IN
    (SELECT offer_id
     FROM offer_att oa,
          att a
     WHERE a.title_pl IN (41,
                          2,
                          4,
                          6)
       AND a.id = oa.att_id);

P.S。 Here是一个小提琴。

答案 1 :(得分:0)

如果您只想获取包含所有4个属性(41,2,4,6)的商品,那么您应该使用下一个查询

SELECT
    o.id
    o.title_pl
FROM
    offer o INNER JOIN offer_att oa ON o.id = oa.offer_id AND oa.att_id IN (41,2,4,6)   
GROUP BY o.id
HAVING COUNT(DISTINCT oa.att_id) = 4

如果您要获取至少包含一个属性(41或2或4或6)的商品,请使用以下商品:

SELECT
    o.id
    o.title_pl
FROM
    offer o INNER JOIN offer_att oa ON o.id = oa.offer_id AND oa.att_id IN (41,2,4,6)   

用于为SQL查询生成参数的PHP代码:

<?php
$attributes = array(41, 2, 4, 6);
$count = count($attributes);
$list = implode(',', $attributes);
$query = '
    SELECT
        o.id
        o.title_pl
    FROM
        offer o INNER JOIN offer_att oa ON o.id = oa.offer_id AND oa.att_id IN (' . $list . ')  
';
$db->query($query);
?>