4

例如,我有一个电视列表,每台电视都有一些属性,例如:品牌(三星、索尼等)、尺寸(80 厘米、116 厘米等)、SmartTv(是,否)。

我有以下架构:

   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,
)

如果我想要三星的所有电视,我会这样说:

    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')

这很好,但如果我想要:所有智能电视的三星电视:

     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')

我应该如何使用多个 AND 修复查询?

4

1 回答 1

6

第一个想法,在我的脑海中 - 尝试用内部查询替换你的连接,并计算匹配属性的数量:

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
                   );
于 2013-10-12T11:44:19.690 回答