2014-10-29 89 views
0

首先表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

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

回答

0

我会做到这一点使用的聚集和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; 
+0

以上解决方案不起作用 – user3244871 2014-10-29 12:38:42

+0

如果所有三个选项均为真,我只需要一个属性 – user3244871 2014-10-29 13:09:17

+0

select p.id,p.nam È 从属性p INNER通过p.id 具有总和(po.meta_name = '露台')> 0和 总和(po.meta_name = '阳台')JOIN property_option PO ON p.id = po.property_id 组> 0和 sum(po.meta_name ='garaj')> 0 – user3244871 2014-10-29 14:27:47

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 
+0

无法使用此解决方案 – user3244871 2014-10-29 12:45:07

0

这是确切的答案

选择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