查询查找表的最佳实践
我正在尝试找出一种查询属性特征查找表的方法。
我有一个房产表,其中包含出租房产信息(地址、租金、押金、卧室数量等)以及另一个代表该房产特征(游泳池、空调、现场洗衣房等)的表(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 查询会是什么样子? 这可能吗? 有更好的解决方案吗?
感谢您的帮助和见解。
I am trying to figure out a way to query a property feature lookup table.
I have a property table that contains rental property information (address, rent, deposit, # of bedrooms, etc.) along with another table (Property_Feature) that represents the features of this property (pool, air conditioning, laundry on-site, etc.). The features themselves are defined in yet another table labeled 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)
Let say someone wants to search for property that has air conditioning, and a pool and laundry on-site. How do you query the Property_Feature table for multiple features for the same property if each row only represents one feature? What would the SQL query look like? Is this possible? Is there a better solution?
Thanks for the help and insight.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就数据库设计而言,您的方法是正确的。 它已正确标准化。
对于查询,我将简单地使用存在,如下所示:
其中 key_air_conditioning 和 key_pool 显然是这些功能的键。
即使对于大型数据库,性能也可以。
In terms of database design, yours is the right way to do it. It's correctly normalized.
For the query, I would simply use exists, like this:
Where key_air_conditioning and key_pool are obviously the keys for those features.
The performance will be OK even for large databases.
下面的查询将查找池中的所有属性:
我使用内部联接而不是 EXISTS,因为它往往会更快一些。
Here's the query that will find all the properties with a pool:
I use inner joins instead of
EXISTS
since it tends to be a bit faster.您还可以执行以下操作:
显然,如果您的前端在用户选择功能项时捕获功能项的 fid,则可以省去与功能的连接并直接约束 fid。 您的前端会知道所选功能的数量是多少,因此确定上面“3”的值很简单。
在性能方面,将其与上面的 tekBlues 结构进行比较; 根据您的数据分布,其中任何一种查询都可能是更快的查询。
You can also do something like this:
Obviously, if your front end is capturing the fids of the feature items when the user is selecting them, you can dispense with the join to Feature and constrain directly on fid. Your front end would know what the count of features selected was, so determining the value for "3" above is trivial.
Compare it, performance wise, to the tekBlues construction above; depending on your data distribution, either one of these might be the faster query.