MySQL查询与一对多的关系与匹配

首先表MySQL查询与一对多的关系与匹配

物业搜索

id Name 

1 ABC

2 XYZ

3 GHQ

Property_options

id property_id option 

1 1 terrace

2 1 balcony

3 1 garaj

1 2 terrace

2 2 balcony

3 2 garaj

我想有三个过滤财产选项(terrace,balconygaraj

如果用户检查三个选项,那么只有那些属性会有三个选项不是两个或一个。

回答:

我会做到这一点使用的聚集和group by

select p.propertyid 

from property p

group by p.propertyid

having sum(property_option = 'terrace') > 0 and

sum(property_option = 'balcony') > 0 and

sum(property_option = 'garaj') > 0;

条件的每个计算的时候出现的属性的数量。这是一个灵活的方法。如果你想前两个,但不是 “garaj”,你可以使用:

having sum(property_option = 'terrace') > 0 and 

sum(property_option = 'balcony') > 0 and

sum(property_option = 'garaj') = 0;

回答:

试试这个:

select Name from Property where id in (select property_id from Property_Options where Property_Option = 'terrace ' and Property_Option = 'balcony ' and Property_Option = 'garaj')a 

回答:

这是确切的答案

选择p.id,p.name从属性P INNER JOIN property_option PO P上.id = po.property_id group by p.id having sum(po.meta_name ='terrace')> 0 and sum(po.meta_name ='balcony')> 0 and sum(po.meta_name ='garaj')> 0

以上是 MySQL查询与一对多的关系与匹配 的全部内容, 来源链接: utcz.com/qa/262346.html

回到顶部