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

时间:2018-06-13 18:31:44

标签: 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

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

    select property_id 
    from properties_features left join Features 
    on properties_features.feature_id = Features.feature_id
    where properties_features.feature_id in 
      (select feature_id
          from Features 
         where feature_name in ('pool', 'garden'))
    group by property_id 
    having count(distinct properties_features.feature_id)>1

这是一个有效的方法:

http://www.sqlfiddle.com/#!9/dcbc5b7/3

答案 1 :(得分:0)

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 

这将获得所有具有池和花园的Property ID,而无需任何连接或硬编码数据。

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

最好不要使用任何硬编码值来获得更多动态查询。