sql通过连接表选择

时间:2014-03-05 13:00:44

标签: sql jointable

Hy all,

我需要一点帮助来编写一个选择......问题如下:

我有以下表格:

help
+----+-------+---------+
| id | title | content |
+----+-------+---------+
| 1  | a     | acont   |
| 2  | b     | bcont   |
+----+-------+---------+

helptag
+----+------+
| id | name |
+----+------+
| 1  | atag |
| 2  | btag |
+----+------+

helphelptag(join table)
+--------+-----------+
| helpid | helptagid |
+--------+-----------+
| 1      | 1         |
| 1      | 2         |
| 2      | 2         |
+--------+-----------+

我需要选择那些帮助,哇有我给的ID。 因此,例如,如果我给tag_id 2,则比帮助1和2都要好 但如果我给tag_id 1和2,而不仅仅是帮助1。

我尝试过使用ID [tag_ids]的leftjoin,但如果我给出1和2,它会给予帮助。

1 个答案:

答案 0 :(得分:0)

这是“set-within-sets”查询的示例。我喜欢使用聚合和having子句来解决这个问题。第一个问题:

select helpid
from helphelptag
group by helpid
having sum(case when helptagid = 2 then 1 else 0 end) > 0;

对于第二个,只需添加另一个条件:

having sum(case when helptagid = 2 then 1 else 0 end) > 0 and
       sum(case when helptagid = 1 then 1 else 0 end) > 0;

每个条件都会计算与给定条件匹配的行数。