如何形成一对多关系的 SQL 查询?
我有两个 MySQL 表:house
和 features
。这是一个房地产网站。
house
具有以下结构:
id | address | ... some other fields
features
具有以下结构:
id | house_id | feature | value
正如您所猜测的,一所房子可以有多个功能,因此存在 1:n 关系。
现在,我正在实现一个房屋搜索表单。我需要根据用户选择的功能来过滤结果。
示例场景:获取具有车库和花园功能的所有房屋,以及这些房屋的功能列表。
满足我的需求的最佳查询是什么?我不熟悉JOIN操作,所以我需要你的帮助!
(可选)如果您可以提供特定于 Yii 框架的解决方案,那就太棒了:)
I have two MySQL tables: house
and features
. This is for a real estate website.
house
has this structure:
id | address | ... some other fields
features
has this structure:
id | house_id | feature | value
as you can guess, a house can have multiple features, so a 1:n relationship exists.
Now, I'm implementing a search form for houses. I need to filter the results based on the features selected by the user.
Sample scenario: get all houses which have the features garage
and garden
, and a list of features in those houses.
What would be the best query to suit my needs? I'm not familiar with JOIN operations, so I need your help!
(OPTIONAL) If you can provide a Yii Framework-specific solution, it would be awesome :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 Yii,则无需手动加入。
如果您使用 MySQL(通过 SQLite)和使用 InnoDB 表(通过 MyISAM 表)会更容易。
您需要创建从 Features(house_id 列)到 Houses(house_id 列)的外键。
如果您使用 Gii 构建模型,那么它将自动为您创建“关系”函数。
然后在 Yii 中,您可以调用 House->features 来获取特征行数组。
您可以在 Fill() 调用中传递 CDbCriteria 对象来过滤用户选择的房屋。
You don't need to join it manually if you are using Yii.
It's easier if you use MySQL (over SQLite) and if you use InnoDB tables (over MyISAM tables).
You need to create a foreign key from Features (house_id column) to Houses (house_id column)
If you build your model using Gii, then it will create the "relation" function for you automatically.
Then in Yii, you would call House->features to get an array of feature rows.
You can pass a CDbCriteria object in the Fill() call to filter the houses that the user selected.
如果您仅需要房屋表中的列:
SELECT * from HOUSE where ID in (SELECT ID from FEATURES where FEATURE IN('GARDEN','GARAGE')) ;
如果您需要完整的详细信息:
选择 *
从 HOUSE H 加入功能 F ON H.HOUSE_ID = F.HOUSE_ID
地点在 ('花园','车库');
If you need only the columns from the House table:
SELECT * from HOUSE where ID in (SELECT ID from FEATURES where FEATURE IN('GARDEN','GARAGE'));
If you need the entire details:
SELECT *
FROM HOUSE H JOIN FEATURES F ON H.HOUSE_ID = F.HOUSE_ID
WHERE FEATURE IN ('GARDEN','GARAGE');