我认为这对于那些经常使用 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
但我真正想要的是只选择 tag_id 为“1”和“5”的 ph_id。
因此,正如您可能看到的,我正在尝试根据多个标签过滤选择。我想结束:
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 NO WORK 所建议的那样
基本上我从表'tags'中获取所有选定标签的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_id 匹配的 ph_id 的数组。
感谢大家的帮助。