I have these two different queries.
This query pulls the records from “posts” table as per their replies counter. Only posts with replies are returned with this query:
SELECT posts.title, posts.num, posts.status, COUNT( posts_replies.post_num) AS count
FROM posts_replies
INNER JOIN posts ON ( posts_replies.post_num = posts.num )
WHERE posts.status = 1
AND posts.category='uncategorized'
GROUP BY posts.num
And this is a new query that i want to merge with the above one to pull and sort records as per gps.
SELECT num, title, ( 3959 * acos( cos( radians( 37 ) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians( -122 ) ) + sin( radians( 37 ) ) * sin( radians( lat ) ) ) ) AS distance
FROM posts
HAVING distance <75
ORDER BY distance
This query uses the columns lat and long to return records that are within the 75 miles radius of the user.
I am not a sql expert and don’t know how to merge both of the queries to gather results having the following criteria:
- Only return posts with replies
- Sort by their distance
- Sort by their number of replies
Any help would be highly appreciated.
Thanks!
The
havingclause in the second query does not look correct. In most dialects of SQL is would not be allowed without agroup by. I forget if MySQL t implicitly treats the whole query as an aggregation (returning one row) or if thehavinggets converted to awhere. In either case, you should be explicit and usewherewhen there are no aggregations.You can just combine them by putting in the
whereclause. I would do it with a subquery, to make the variable definitions clearer: