Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

mysql - Order Results By Occurrence

I have the following two tables.

BookmarkTag ( BookmarkID, TagID ) Tag ( TagID, Title)

Currently I am selecting all the tags with the appropriate BookmarkID. The problem is I want to only select the tag once to avoid duplication in the result and also only bring back the tags the occur the most.

This is my current SQL query:

SELECT Tag.Title 
FROM `Tag` INNER JOIN BookmarkTag 
WHERE BookmarkTag.BookmarkID = 1 AND Tag.TagID = BookmarkTag.TagID'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to put the join condition in an ON clause after the JOIN keyword. Not in the where clause.
You were mixing SQL89 with SQL92 syntax. This may work I haven't tested, but this is faster.

SELECT Tag.Title 
FROM `Tag` t
INNER JOIN BookmarkTag b ON (t.tagid = b.tagid)
WHERE B.BookmarkID = 1
GROUP BY t.tagid
ORDER BY count(*) DESC

In order to make the results unique per tag, do a group by on tagid.
Then you can order by occurrence by using count(*) to see make the tags with the highest occurrence float to the top.
(try to always use count(*) because it is faster than count(afield) )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...