2

以前曾以不同的方式提出过这个问题,但我似乎无法得到适合我确切需要的东西。

此处的目标是进行搜索查询,该查询根据所选标签返回照片。许多标签可以同时应用于过滤器,这需要使查询只返回选择了所有标签的照片。想想在执行基本关键字搜索后您正在缩小结果范围的任何主要网上商店。

表 1:照片 ID|标题|描述|URL|已创建

表 2:PhotosTagsXref ID|PhotoId|TagId

表 3:照片标签 ID|标题|类别

是)我有的:

SELECT p.* FROM `PhotosTagsXref` AS pt
LEFT JOIN `Photos` AS p ON p.`ID` = pt.`PhotoId`
LEFT JOIN `PhotosTags` AS t ON pt.`TagId` = t.`ID`
WHERE p.`Description` LIKE "%test%" AND 
????
GROUP BY p.`ID`
ORDER BY p.`Created` DESC LIMIT 20

这 ????是我尝试了很多东西但被难住的地方。问题是我可以轻松找到包含带有一个或另一个标签的照片的结果集,但如果应用 2、3 或 4 个标签,我们只需要返回在数据库中包含所有这些标签条目的照片。我认为这将涉及组合结果集,但不能 100% 确定。

示例:照片 1 标签:蓝色、白色、红色 照片 2 标签:蓝色

搜索带有“蓝色”标签的照片会返回两张照片,搜索带有“蓝色”和“白色”标签的照片只会返回照片 1。

4

3 回答 3

1

假设请求的标签集是 ( red, blue) 你可以这样做:

SELECT * FROM `Photos` 
WHERE `Description` LIKE "%test%" 
AND `ID` IN (
  SELECT pt.`PhotoId` FROM `PhotosTagsXref` AS pt
  JOIN `PhotosTags` AS t ON pt.`TagId` = t.`ID`
  WHERE t.Title in ('red','blue') /* your set here */
  GROUP BY pt.`PhotoId` HAVING COUNT(DISTINCT t.`TagId`)=2 /* # of tags */
  )
ORDER BY `Created` DESC LIMIT 20

显然,标签集需要动态创建,以及它的计数。

注意:我计算DISTINCT TagIDs 是因为我不知道你的表的约束。如果PhotosTagsXRef有一个 PK/UNIQUE ( PhotoId, TagId) 并且PhotosTags有一个 PK/UNIQUE ( TagId),那么COUNT(*)就足够了。

于 2013-10-09T16:03:46.990 回答
0

诚然有点丑。但假设 PhotosTags.Category 有“蓝色”、“白色”等,请尝试沿着这条线。

SELECT p.* 
From `Photos` AS p
WHERE p.`Description` LIKE "%test%" AND 
  AND Exists
      ( Select 1 FROM `PhotosTagsXref` AS pt
        Inner JOIN `PhotosTags` AS t ON pt.`TagId` = t.`ID`
        Where pt.`PhotoId` = p.`ID`
          And t.Category = 'FirstCatToSearch'
      )   
  AND Exists
      ( Select 1 FROM `PhotosTagsXref` AS pt
        Inner JOIN `PhotosTags` AS t ON pt.`TagId` = t.`ID`
        Where pt.`PhotoId` = p.`ID`
          And t.Category = 'SecondCatToSearch'
      )   
  AND Exists
      ( ...
      )   
      ...
于 2013-10-09T15:54:41.487 回答
0
SELECT p.* FROM `PhotosTagsXref` AS pt
LEFT JOIN `Photos` AS p ON p.`ID` = pt.`PhotoId`
LEFT JOIN `PhotosTags` AS t ON pt.`TagId` = t.`ID`
inner join (select PhotoId from PhotosTagsXref 
             LEFT JOIN `PhotosTags` AS t 
             ON pt.`TagId` = t.`ID`
             where (t.title = 'cond 1' or t.title = 'cond 2' ...)
             --where t.title in (list condition)    **this works as well**
             having count(1) = (count of conditions) ) filter
  on filter.photoID = pt.PhotoID
WHERE p.`Description` LIKE "%test%"
GROUP BY p.`ID`
ORDER BY p.`Created` DESC LIMIT 20

这应该可行,我对过滤器和连接使用的列做了一些假设,您可能需要重新工具...内部连接用作过滤器,并且应该只提取匹配数等于总数的记录提交的比赛数量。现在您只需要一种语言来插入这些条件和条件计数值。

于 2013-10-09T15:59:19.897 回答