数据库设计:存储多个选项的多个选项的最佳方式

时间:2013-01-11 17:04:32

标签: mysql database database-design

所以我想确定最好的方法是什么: 我将尝试尽可能简单,但提供足够的信息

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

我有一张桌子:

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

一些例子是:值是ref表中更多信息的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 )

或者更好的是,不是让一个表中的键和everthing都有每个key.option,每个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

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

我希望这是有道理的 谢谢你的帮助

1 个答案:

答案 0 :(得分: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过滤,你将只选择符合所有标准的汽车。