繁体   English   中英

MySQL选择复杂查询

[英]Mysql select complex query

标题含糊不清,我很抱歉,但是我的英语确实无法让它更具体。

我有一个名为posts__tags表,用于将post idstag ids与以下列相关联

record_idpost_idtag_id 这是一个示例样本

record_id | post_id | tag_id  
1         |    1    |   1     
2         |    1    |   2     
3         |    1    |   3     
4         |    2    |   2     
5         |    3    |   1     
6         |    3    |   3     
7         |    4    |   2     
8         |    4    |   3     
9         |    4    |   4   

我有一个PHP函数,其中有一个tag_ids数组作为参数。 例如,假设我的参数是array(2,3) 我需要选择与tag_id = 2 AND tag_id = 3相关联的所有post_id。

在上面的示例中,我应该得到1和4个post_id,因为只有那些与2和3个tag_id都相关联。

用MySQL查询实现此目标的最佳方法是什么?

提前致谢

尝试这个

select distinct post_id from table_name where tag_id in (2,3)
select post_id from posts__tags where tag_id in (1,2) group by post_id having count(*)=2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM