对于那些使用MYSQL的人来说,我认为这将是一件容易的事,但我无法完全理解它......主要是因为不知道正确的术语来搜索。MYSQL匹配满足多个条件的条目
基本上我有一个表映射标签ID到照片ID,称为tag_map。当我执行此查询:
SELECT * FROM tag_map WHERE tag_id='1' OR tag_id='5';
我得到如下结果:
ph_id tag_id
1 1
2 1
5 1
7 5
8 1
9 5
10 5
11 1
12 1
13 1
但我真正想要的是只选择ph_id有两个“1” TAG_ID和“5”。
因此,正如你可能看到的,我试图根据多个标签过滤选择。我想结束了:
ph_id tag_id
7 1
7 5
8 1
8 5
11 1
11 5
所以ph_id 7,第8和11参考TAG_ID 1和5
希望是有道理的。
谢谢。
解决方案
由于我查询的动态特性(用户选择任意数量的可用标签为“缩小选择)我去一个PHP的解决方案,通过@YU没有工作的建议
基本上我从表'标签'中获取所有选定标签的tag_id
然后,我从我的表tag_map中选择了映射到所选tag_ids的所有照片ID(ph_id)。
然后我减少这个向下发生的相同的次数作为所选标签的数量ph_ids:
$numTags = count($arTagId); //$arTagId is an array of the selected tags
// get only photo ids that match both tags
$arPhId = array();
// in arPhId, find ph_ids that have occurances equal to $numTags
$arPhIdCnt = array_count_values($arPhIdAll); //$arPhIdAll is array of all ph_id that match all selected tag_ids
foreach($arPhIdCnt as $pid => $pidQty) {
if($pidQty == $numTags) {
$arPhId[] = $pid;
}
}
所以我最终只匹配两者tag_ids该ph_ids的阵列。
感谢大家的帮助。
我开始怀疑PHP是否可能是路线...无论如何,我使用PHP构建查询。 – j0nr
PHP确实比较容易,但对于您的Web服务器而言性能会降低。您只需使用他们的tag_ids保存所有ph_ids。然后你使用“array_count_values($ ph_id)”,只保存那些函数值高于1的地方。 –