我有一张像
这样的表格asset_id tag_id
1 2
2 3
3 1
2 15
5 6
6 3
6 15
现在,我想要所有带有标签3和15的记录,在上面的例子中它将是2和6,如何在没有连接的情况下得到这个? 我可以用这个得到结果,但我想知道我是否可以取消加入,如果我想获得标签1,2和3的所有资产,我该如何解决?
select * from table a, table b where a.tag_id=3 and b.tag_id=15 and a.asset_id=b.asset_id
这是我的示例数据。
+------+----------+------------+--------+
| id | asset_id | asset_type | tag_id |
+------+----------+------------+--------+
| 5349 | 235362 | question | 5 |
| 5350 | 235362 | question | 37 |
| 5351 | 235362 | question | 36 |
| 5352 | 235362 | question | 7 |
| 5353 | 235362 | question | 106 |
| 6657 | 235234 | question | 5 |
| 6658 | 235234 | question | 36 |
| 6659 | 235234 | question | 5 |
| 6660 | 235234 | question | 38 |
| 6661 | 235234 | question | 38 |
| 6662 | 235234 | question | 11 |
| 6663 | 235234 | question | 11 |
| 8135 | 1234 | | 5 |
| 8136 | 1234 | | 36 |
| 8137 | 1234 | | 106 |
+------+----------+------------+--------+
现在,如果我运行查询
select group_concat(asset_id) from co_asset_tags where tag_id in (5,36,106) group by asset_id having count(*)=3
我得到了
+------------------------+
| group_concat(asset_id) |
+------------------------+
| 1234,1234,1234 |
| 235234,235234,235234 |
| 235362,235362,235362 |
+------------------------+
这是错误的,只有1234和235362应该在那里。
答案 0 :(得分:0)
您可以使用Group by
并拥有:
select asset_id from table where tag_id in (...) group by asset_id having count(*) =<number of tag_id's>
为您的例子:
select asset_id from table where tag_id in (1,2,3) group by asset_id having count(*) =3
查看我的sqlfiddle