MySQL 获取具有多个标签 ID 的事物的唯一列表

MySQL get unique list of things with multiple tag IDs

我有 2 个 table 名为 tagsthings,它们都包含一个 id 和一个 name 列。然后,还有第三个 table:thing_tags。其中有这样的数据:

╔═══════╤═════════╗
║ tagid │ thingid ║
╟───────┼─────────╢
║     6 │       1 ║
║     6 │       2 ║
║    12 │       1 ║
║    12 │       2 ║
║    12 │       3 ║
║    15 │       4 ║
║    16 │       4 ║
║    21 │       5 ║
╚═══════╧═════════╝

这 2 列具有对各自 table 的 id 列的外键引用。

我想做的是获取同时具有标签 #6 和 #12 的唯一事物 ID 的列表,因此在这种情况下,结果将是 ID 12,而不是 3,然后在 things table 中找到具有这些 ID 的元素并检索它们。这是我当前的 SQL 查询:

SELECT th.*
FROM thing_tags t
LEFT JOIN things th ON t.id = th.id
WHERE t.id IN (12,6)
ORDER BY th.name ASC

这没有按照我想要的方式工作,因为它还给了我 table 的第三个结果,并且 returns 多次正确的结果。我如何修改此查询,以便只返回绑定到所有指定 tagid 的那些 things,而不仅仅是一个,最后没有重复的行?

in(...) 是一个 or 比较,而你需要一个 and。您无法更改 in 行为,但您可以向查询的其余部分添加额外的逻辑以使 in 表现得好像它确实具有 and 语义:

SELECT field1, COUNT(field2) AS cnt
FROM yourtable
WHERE field2 IN (6, 12)
GROUP BY field1
HAVING cnt = 2

count() 告诉您有多少 in 字段存在,然后您使用 having 子句来强制执行您真正想要的数量。在你的情况下,你只想要 2,所以你使用 = 2.

having cnt > 2 在语义上等同于 "has AT LEAST 2".

这是我最后的尝试::)

select things.* from things
inner join thing_tags a on a.thingid = things.id and a.tag_id = 6
inner join thing_tags b on b.thingid = things.id and b.tag_id = 12