添加连接操作后,toxi样式标签查询中断



我正试图从一个出租车风格的数据库中选择项目。数据库的结构如下:

表">

歌曲":

<表类>指数标题…tbody><<tr>"a001">"title1">…"a002">"title2">…

删除过滤并使用条件聚合来检查您的标记是否在所有标记中存在。

SELECT s.title, s.description, GROUP_CONCAT(t.tag_name) AS tags
FROM      songs s
LEFT JOIN tagmap tm
ON s.index = tm.item_index
LEFT JOIN tags t 
ON tm.tag_index = t.tag_index
GROUP BY s.title, s.description
HAVING COUNT(CASE WHEN t.tag_index IN (2,3) THEN 1 END) = 2

注意,此解决方案假定没有重复的标记。如果您可以将标题多次关联到单个标记,则应该将HAVING子句中的条件拆分为如下所示:

HAVING MAX(tag_index=2) = 1 
AND MAX(tag_index=3) = 1

这确保了至少有一个真值(相应的标签存在)。

不需要创建第二个桥表。

也不要把逗号分隔的连接和其他连接混在一起,因为逗号分隔是旧的风格

基本上

SELECT MAX(s.title) as tiltle, MAX(s.description) as description, GROUP_CONCAT(t2.name SEPARATOR ', ') as tags
FROM songs s  INNER JOIN tagmap tm ON s.index = tm.item_index
INNER JOIN   tags t2 ON tm.tag_index = t2.tag_index
WHERE (tm.tag_index IN (7,3))
GROUP BY s.item_index 
HAVING COUNT(s.item_index)=2 
ORDER BY s.date DESC

来获取所有项目所需的所有标签。有这些标签的索引

SELECT MAX(s.title) as tiltle
#, MAX(s.description) as description
, GROUP_CONCAT(t2.name SEPARATOR ', ') as tags
FROM SONGS s  INNER JOIN TAGMAP tm ON s.index = tm.item_index
INNER JOIN   TAGS t2 ON tm.tag_index = t2.tag_index
WHERE s.index IN ( SELECT item_index FROM TAGMAP WHERE tag_index IN ('t003','t004'))
GROUP BY s.index 
HAVING COUNT(tm.item_index)=3 
#ORDER BY s.date DESC
标记th>

最新更新