在一个表中获取行,在另一个表中获取多行

5fjcxozz  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(192)

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

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

功能表:

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

和一个表属性\u功能:

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

例如,我想检索只有pool和garden的属性id

8xiog9wr

8xiog9wr1#

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

这将获得所有的属性标识,这些标识有一个没有任何连接或硬编码数据的游泳池和花园。
如果任何特性名称被更改,例如:from pool->pool,这也将在将来对您有所帮助。此查询仍然有效!:)
对于更动态的查询,最好不要使用任何硬编码值。

fjaof16o

fjaof16o2#

你可以试试这个:

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

相关问题