我试图想出一种查询属性特征查找表的方法。

我有一个属性表,其中包含出租物业信息(地址,租金,押金,卧室数量等)以及代表该物业特征的另一张表(Property_Feature)(游泳池,空调,洗衣房 - 网站等)。功能本身在另一个标记为功能的表中定义。

Property
    pid - primary key
    other property details

Feature
    fid - primary key
    name
    value

Property_Feature
    id - primary key
    pid - foreign key (Property)
    fid - foreign key (Feature)

假设有人想搜索有空调的房产,还有现场的游泳池和洗衣房。如果每行仅代表一个功能,如何在Property_Feature表中查询同一属性的多个功能? SQL查询会是什么样的?这可能吗?有更好的解决方案吗?

感谢您的帮助和见解。

有帮助吗?

解决方案

在数据库设计方面,你的是正确的方法。它正确归一化。

对于查询,我只想使用exists,如下所示:

select * from Property
where 
exists (select * from Property_Feature where pid = property.pid and fid = 'key_air_conditioning')
and
exists (select * from Property_Feature where pid = property.pid and fid = 'key_pool')

其中key_air_conditioning和key_pool显然是这些功能的关键。

即使对于大型数据库,性能也可以。

其他提示

以下是查找池中所有属性的查询:

select
    p.*
from
    property p
    inner join property_feature pf on
        p.pid = pf.pid
    inner join feature f on
        pf.fid = f.fid
where
    f.name = 'Pool'

我使用内部联接而不是 EXISTS ,因为它往往会更快一点。

您也可以这样做:

  SELECT * 
    FROM Property p
   WHERE 3 =
         ( SELECT COUNT(*)
             FROM Property_Feature pf
                , Feature f
            WHERE pf.pid = p.pid
              AND pf.fid = f.fid
              AND f.name in ('air conditioning', 'pool', 'laundry on-site')
         );

显然,如果您的前端在用户选择时捕获要素项的fid,则可以省去连接到要素并直接在fid上进行约束。您的前端会知道所选功能的数量是多少,因此确定“3”的值是多少。以上是微不足道的。

将性能明智地与上面的tekBlues构造进行比较;根据您的数据分布,其中任何一个可能是更快的查询。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top