0

所以我试图确定什么是最好的方法:我会尽量让这个尽可能简单,但要提供足够的信息

我有一个包含大型数据集的数据库。对于此示例,每辆车都是某人正在寻找的汽车

我有一张桌子:

CREATE TABLE cars (
`car_id` INT(10),
`car_name` VARCHAR(20)
)  

和选项表

CREATE TABLE `car_selected_options` (
`car_sel_id`   INT       NOT NULL AUTO_INCREMENT,
`car_id`       INT       //the id of the car record created
`value`        INT       //id of info in a ref table
`key`          VARCHAR(20)   //from the car_option_reference,
)

一些例子是:值是参考表中更多信息的ID(注意两个电子)

car_id=1, value='10',    key='exterior_color'  10='red'
car_id=1, value='21',    key='interior_color'  21='blue' 
car_id=1, value='100',   key='electronics'     100='radio'
car_id=1, value='101',   key='electronics'     101='nav'

我需要找到所有红色的汽车 ID,并且有导航和收音机,我正在做类似的事情:

SELECT distinct(c.car_id)
FROM `car` c 
   INNER JOIN `car_selected_options` AS o ON c.car_id = o.car_id
WHERE 
o.car_sel_id IN 
        ( SELECT car_sel_id 
            FROM car_selected_options so 
            WHERE so.`key` = 'exterior_color' 
              AND so.value IN ('10' ) AND b.buyer_id = bm.buyer_id )
    AND
o.car_sel_id IN 
        ( SELECT car_sel_id 
            FROM car_selected_options so 
            WHERE so.`key` = 'electronics'  
              AND so.value IN ('100','101' ) AND b.buyer_id = bm.buyer_id )

还是最好不要在一个表中使用键和所有内容,而是将每个 key.option 与每个事物的单独表分开,例如:

car_exterior_color (could have one entry per car or multiples if this person is ok with a red or a blue colored car)
car_interior_color 
car_electronics

而不是做这些多个子选择(可能很多),做多个内部连接?

我希望这是有道理的,感谢您的帮助

4

1 回答 1

0

您发布的查询似乎缺少某些内容,因为我看不到“b”和“bm”表是什么。忽略该子句,您可以大大简化查询,而无需执行多个子选择:

SELECT c.car_id
FROM `car` c 
   INNER JOIN `car_selected_options` AS o ON c.car_id = o.car_id
WHERE 
   (o.key = 'exterior_color' AND o.value = 10) OR
   (o.key = 'electronics' AND o.value = 100) OR
   (o.key = 'electronics' AND o.value = 101) OR
GROUP BY c.car_id
HAVING COUNT(*) = 3;

在这种情况下,“3”是您应用的标准数量。这里的诀窍是,对于每辆匹配的汽车,您应该恰好有三个匹配的行,所以如果您按 car_id 分组,并按 count(*) = 3 过滤,您将只选择符合所有条件的汽车。

于 2013-01-11T17:57:59.197 回答