简体   繁体   English

Mysql产品过滤器有多个选项

[英]Mysql product filters with multiple options

for example I have a list o TVs, and each TV has some attributes like: Brand(Samsung,Sony etc..), Size(80cm, 116 cm etc), SmartTv(yes, no). 例如我有一个电视列表,每个电视都有一些属性,如:品牌(三星,索尼等..),尺寸(80厘米,116厘米等),SmartTv(是的,没有)。

I have the following schema: 我有以下架构:

   CREATE TABLE `products` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(150) NOT NULL,
)

CREATE TABLE `attributes` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(20) character set latin1 NOT NULL
)

CREATE TABLE `attributes_entity` (
  `product_id` int(11) NOT NULL,
  `attribute_id` int(11) NOT NULL,
  `value_id` int(11) NOT NULL,
)

CREATE TABLE `attributes_values` (
  `id` int(11) NOT NULL auto_increment,
  `value` varchar(255) default NULL,
)

If i want all TV from samsung i say like this: 如果我想要来自三星的所有电视,我会这样说:

    SELECT
    `p`.`id`,
    `p`.`name`
FROM `attributes_entity` `ae`
    INNER JOIN `products` `p` ON `ae`.`product_id`=`p`.`id`
    INNER JOIN `attributes` `a` ON `ae`.`attribute_id`=`a`.`id`
    INNER JOIN `attributes_values` `av` ON `ae`.`value_id`=`av`.`id`
WHERE (`a`.`name`='samsung' AND `av`.`value`='samsung')

This is great but what if I want: All Samsung TVs that are smartTv: 这很棒,但如果我想要的话:所有三星电视都是smartTv:

     SELECT
    `p`.`id`,
    `p`.`name`
FROM `attributes_entity` `ae`
    INNER JOIN `products` `p` ON `ae`.`product_id`=`p`.`id`
    INNER JOIN `attributes` `a` ON `ae`.`attribute_id`=`a`.`id`
    INNER JOIN `attributes_values` `av` ON `ae`.`value_id`=`av`.`id`
WHERE (`a`.`name`='samsung' AND `av`.`value`='samsung')
//imposible query
and (`a`.`name`='smartv' AND `av`.`value`='yes')

How should i fix the query with multiple ANDs? 我应该如何修复多个AND的查询?

First idea, off the top of my head - try replacing your joins with an inner query, and count the number of matching attributes: 第一个想法,在我的脑海中 - 尝试用内部查询替换你的连接,并计算匹配属性的数量:

SELECT `p`.`id`, `p`.`name`
FROM   `products` `p`
WHERE   `p`.`id` IN (SELECT     `ae`.`product_id`
                     FROM       `attributes_entity` `ae`
                     INNER JOIN `attributes` `a` ON `ae`.`attribute_id`=`a`.`id`
                     INNER JOIN `attributes_values` `av` ON `ae`.`value_id`=`av`.`id`
                     WHERE       ((`a`.`name`='samsung' AND `av`.`value`='samsung') OR
                                  (`a`.`name`='smartv' AND `av`.`value`='yes'))
                     HAVING COUNT(*) >= 2 -- number of matching attributes required
                    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM