Reputation: 1605
first table: posts
ID post unix_timestamp upvotes
-----------------------------------
118 mmmm 1360662045 4
119 kdkdk 1360662074 2
120 dkcjf 1360662012 3
121 dkcmv 1360662025 1
and some other fields
second table: post_tags
ID post_id tagname
-----------------------
1 118 #test
2 118 #iseeyou
3 119 #sleepy
MYSQL query that i ran.
SELECT p.id, p.post, p.timestampfull FROM posts p,
post_tags pt WHERE pt.tagname IN ('#test','#iseeyou')
AND p.post LIKE '%united states%'
AND p.id = pt.post_id
GROUP BY p.id
HAVING COUNT( pt.tagname ) = 2
ORDER BY p.upvotes DESC , p.unix_timestamp DESC
In my search application, i am trying to fetch the most recent rows that's why p.unix_timestamp
also ordered by upvotes in descending order based on search query which can contain hash tags or plain text or both.
So, if user searches for #test #iseeyou united states
, it should return posts which contain both tags and also the text united states ordered by time stamp and upvotes.
Also, i want the posts with higher upvotes take precedence over being the most recent.
Please advise if my query is correct?
Upvotes: 1
Views: 183
Reputation: 263843
SELECT p.*
FROM posts p
INNER JOIN
(
SELECT a.ID
FROM posts a
INNER JOIN post_tags b
ON a.ID = b.post_ID
WHERE a.post LIKE '%mmmm%' AND
b.tagname IN ('#test','#iseeyou')
GROUP BY ID
HAVING COUNT(DISTINCT b.tagname) = 2
) sub ON p.ID = sub.ID
ORDER BY p.upvotes DESC, p.unix_timestamp DESC
Upvotes: 1