MYSQL - 获取一个表中的行在另一个表中有多个行

标签 mysql

我在一个数据库中有 3 个表:

属性表:

+-------------+--------------------+
| property_id | property_reference |
+-------------+--------------------+
|           1 | RA123              |
|           4 | RT123              |
+-------------+--------------------+

特征表:

+------------+--------------+
| feature_id | feature_name |
+------------+--------------+
|          1 | pool         |
|          2 | garden       |
|          3 | wine house   |
|          4 | parking      |
+------------+--------------+

还有一张表 properties_features:

+-------------+------------+
| property_id | feature_id |
+-------------+------------+
|           1 |          1 |
|           1 |          2 |
|           1 |          4 |
|           4 |          1 |
|           4 |          2 |
|           4 |          3 |
+-------------+------------+

例如,我想检索只有游泳池和花园的属性 ID

最佳答案

select distinct property_id  from properties_features
where feature_id  IN (1,2) and property_id  in(select property_id  from properties_features where feature_id  IN(1,2) group by property_id  having COUNT(property_id ) > 1)
order by property_id 

这将获取所有具有游泳池和花园但没有任何连接或硬编码数据的属性 ID。

如果更改了任何 feature_name,这也会在将来帮助您,例如:from pool -> Pool。这个查询仍然有效! :)

对于更动态的查询,最好不要使用任何硬编码值。

关于MYSQL - 获取一个表中的行在另一个表中有多个行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50843992/

相关文章:

mysql - GWT 和 MySQL : What to use instead of App Engine?

php - mysqli_connect 不工作

python - 无法初始化 Elixir

mysql - 创建一个带有自动递增 id 列的 MySQL View

mysql - 如何在 mysql 中使用 group by 对列求和?

mysql - 识别 mysql 中给定时间段后发生的客户访问

php - 我的表单中的 ® 字符未正确处理

mysql - Rails/Active Record has_and_belongs_to_many 关联 - 获取记录

php - 使用 PHP 从数据库中获取 Blob 并将其用于 HTML 标记

MySQL 选择最便宜的最新 ASK 价格