0

我有以下表格,我想对其进行搜索:

Table A
+----+----------------------------+
| ID | description                |
+----+----------------------------+
|  0 | horse going bad            |
|  1 | Older Years of Resolutions |
|  2 | The knockknock pirate      |
|  3 | The Wish list              |
|  4 | list that's no list        |
+----+----------------------------+

table TAGS
+----+------------+
| ID | tag        |
+----+------------+
|  0 | list       |
|  1 | knockknock |
+----+------------+

table TAGLINKS
+-------+--------+
| TAGID | JOKEID |
+-------+--------+
|   0   |    2   |
|   0   |    3   |
+-------+--------+

当我进行此搜索时:

select A.* from tags
   join taglinks on tagid=tags.id
   join A on A.id=jokeid
where tag in ('list','knockknock') 

给我 A 中的所有条目,它们的标签(或两者)中包含“list”或“knockknock”(2,3)。我正在寻找的是从表 A 中获取条目的查询,这些条目连接到 BOTH list 和 knockknock 标记(仅限 2 个)。

我还通过在表 A 的描述中直接搜索来合并这些数据,这是需要考虑的事情。

现在我有:

select A.* from tags
   join taglinks on tagid=tags.id
   join A on A.id=jokeid
where tag in ('list','knockknock') 

UNION

select * from A where locate('list',description) and locate('knockknock',description)

但我也从表 A 中得到 3 个,我只想要 2 个

4

2 回答 2

2

为确保所有人都有这两个标签'list', 'knockknock',您应该添加GROUP BY子句HAVING

...
WHERE tag in ('list', 'knockknock')
GROUP BY tag
HAVING COUNT(tag) = 2)

就像是:

SELECT A.* 
FROM tags
INNER JOIN taglinks ON tagid = tags.id
INNER JOIN A on A.id=jokeid
WHERE id IN (SELECT id
             FROM tags
             WHERE tag in ('list', 'knockknock')
             GROUP BY tag
             HAVING COUNT(tag) = 2)
于 2013-01-09T14:58:19.913 回答
1

这是一个将标签视为一个集合并查找该集合的属性的示例。我喜欢使用 SQL 的聚合函数,特别是having子句来解决这个问题。

select A.*
from tags join
     taglinks
     on tagid=tags.id join
     A on A.id=jokeid
group by A.id
having max(tag = 'list') = 1 and
       max(tag = 'knockknock') = 1

(注意:这使用了两个 MySQL 特定的语法约定。group by仅在 id 列上;其余是“隐藏列”。并且,表达式tag = 'list'被视为真实值,因此case不需要完整的语句。)

顺便说一句,将其切换到一个或另一个标签很容易:

select A.*
from tags join
     taglinks
     on tagid=tags.id join
     A on A.id=jokeid
group by A.id
having max(tag = 'list') = 1 or
       max(tag = 'knockknock') = 1
于 2013-01-09T15:07:17.213 回答