我遇到了一个问题,即在执行两个表的JOIN时找到具有两个特定“标记”和相同“hashid”的链接
假设我的表格如下:
的链接的
md5 url title numberofsaves
-----------------------------------------
a0a0 google.com foo 200
b1b1 yahoo.com yahoo 100
的标签
md5 tag
---------------
a0a0 awesome
a0a0 useful
a0a0 cool
b1b1 useful
b1b1 boring
我想要返回标记为'有用'和'很棒'
的行用于按1标记查找链接的当前(工作/快速)查询:
SELECT links.title, links.numsaves FROM links LEFT JOIN tags ON links.md5=tags.md5 WHERE tags.tag = 'useful' ORDER BY links.numberofsaves DESC LIMIT 20
阅读article后,我尝试使用以下内容:
SELECT links.title, links.numsaves FROM links LEFT JOIN tags ON links.md5=tags.md5 GROUP BY tags.md5 HAVING SUM(tags.tag='useful') AND SUM(tags.tag='awesome') ORDER BY links.numberofsaves DESC LIMIT 20
任何人都知道解决方案吗?
答案 0 :(得分:9)
问题的类型称为Relational Division
SELECT a.md5,
a.url,
a.title
FROM Links a
INNER JOIN Tags b
ON a.md5 = b.md5
WHERE b.Tag IN ('awesome', 'useful') -- <<== list of desired tags
GROUP BY a.md5, a.url, a.title
HAVING COUNT(*) = 2 -- <<== number of tags defined
输出
╔══════╦════════════╦═══════╗
║ MD5 ║ URL ║ TITLE ║
╠══════╬════════════╬═══════╣
║ a0a0 ║ google.com ║ foo ║
╚══════╩════════════╩═══════╝