mysql where搜索两个相同,mysql:查找具有多个标记和相同ID的行

I'm having an issue figuring the mysql to find links that have two specific 'tags' and the same 'hashid' when doing a JOIN of two tables

Assume my tables look like this:

Links

md5 url title numberofsaves

-----------------------------------------

a0a0 google.com foo 200

b1b1 yahoo.com yahoo 100

Tags

md5 tag

---------------

a0a0 awesome

a0a0 useful

a0a0 cool

b1b1 useful

b1b1 boring

I want to return rows that have tags of BOTH 'useful' and 'awesome'

The current (working/ fast) query for finding links by 1 tag:

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

After reading an article I tried to use the following:

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

This does work but it is so unbelievably slow as to be unusable.

Anyone know the solution?

解决方案

The type of problem is called 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

OUTPUT

╔══════╦════════════╦═══════╗

║ MD5 ║ URL ║ TITLE ║

╠══════╬════════════╬═══════╣

║ a0a0 ║ google.com ║ foo ║

╚══════╩════════════╩═══════╝

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值