mysql选择加入多个条件

时间:2014-05-07 20:39:48

标签: mysql sql

我有三个表:站点,功能和site_feature "网站"像这样的表: 网站

+-----+--------+
|id   | name   | 
+-----+--------+
| 1   | site1  | 
| 2   | site2  |
| 3   | site3  |
| 4   | site4  |
| 5   | site5  |
| 6   | site6  |
| 7   | site7  |
| 8   | site8  |
+-----+--------+

"功能"像这样的表: 特征

+-----+--------+
|id   | feature| 
+-----+--------+
| 1   | fea1   | 
| 2   | fea2   |
| 3   | fea3   |
| 4   | fea4   |
| 5   | fea5   |
| 6   | fea6   |
| 7   | fea7   |
| 8   | fea8   |
+-----+--------+

" site_feature"像这样的表: site_feature

+-----+--------+------------+
|id   | site_id| feature_id | 
+-----+--------+------------+
| 1   | 1      | 1          |
| 2   | 1      | 4          | 
| 3   | 2      | 1          | 
| 4   | 2      | 2          | 
| 5   | 2      | 5          | 
| 6   | 3      | 1          | 
| 7   | 3      | 4          | 
| 8   | 4      | 7          | 
| 9   | 5      | 8          | 
+-----+--------+------------+

我想获得具有我选择的多个功能的网站,例如我想列出具有功能fea1和fea4的网站。

如何构建此查询? 在此先感谢!

2 个答案:

答案 0 :(得分:1)

如果您希望网站具有两项特定功能,并且网站可以包含其他功能以及指定的功能,请将group byhaving一起使用:

select sf.site_id
from site_feature sf join
     feature f
     on sf.feature_id = f.id
where f.feature in ('fea1', 'fea4')
group by sf.site_id
having count(distinct f.feature) = 2;

如果要将其扩展到其他功能,请将它们添加到where子句列表中并增加值2

答案 1 :(得分:0)

您可以使用GROUP BY操作,如下所示:

SELECT
  site_id, 
  count(*)
FROM site_feature
GROUP BY site_id
HAVING count(*) > 1;

以下是GROUP函数的MySQL Reference Manual link