如何形成一对多关系的 SQL 查询?

发布于 2024-10-04 16:27:06 字数 486 浏览 0 评论 0原文

我有两个 MySQL 表:housefeatures。这是一个房地产网站。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ˇ宁静的妩媚 2024-10-11 16:27:06

如果您使用 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.

趴在窗边数星星i 2024-10-11 16:27:06
SELECT * 
FROM HOUSE H JOIN FEATURES F ON H.HOUSE_ID = F.HOUSE_ID
WHERE FEATURE IN ('GARDEN','GARAGE');
SELECT * 
FROM HOUSE H JOIN FEATURES F ON H.HOUSE_ID = F.HOUSE_ID
WHERE FEATURE IN ('GARDEN','GARAGE');
累赘 2024-10-11 16:27:06

如果您需要房屋表中的列:

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');

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文