0

我认为这对于那些经常使用 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 的数组。

感谢大家的帮助。

4

2 回答 2

1

您将不得不自己加入表格,代码可能有点复杂。PHP 将是一个更容易,但不是这样一个高性能的解决方案。

于 2013-10-24T08:37:01.903 回答
0

您必须根据 ph_id 将表与自身连接起来,然后检查 table1 实例的 tab_id col 是否等于 1,table2 实例的 tab_id 是否等于 5。

SELECT t1.* FROM tag_map t1, tag_map t2
WHERE t1.ph_id = t2.ph_id
AND t1.tag_id='1' 
AND t2.tag_id='5';

如果您愿意,可以使用内部连接

SELECT t1.* FROM tag_map t1
INNER JOIN tag_map t2 on t2.ph_id=t1.ph_id
WHERE t1.tag_id='1' 
AND t2.tag_id='5';
于 2013-10-24T08:34:15.793 回答