简体   繁体   English

SQL:要合并的两个不同查询

[英]SQL: Two different queries to merge

I have these two different queries. 我有这两个不同的查询。

This query pulls the records from "posts" table as per their replies counter. 此查询根据其回复计数器从“posts”表中提取记录。 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. 这是一个新的查询,我想与上面的一个进行合并,以按照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. 此查询使用lat和long列返回用户半径75英里范围内的记录。

I am not a sql expert and don't know how to merge both of the queries to gather results having the following criteria: 我不是一个SQL专家,不知道如何合并两个查询来收集具有以下条件的结果:

  1. Only return posts with replies 仅返回包含回复的帖子
  2. Sort by their distance 按他们的距离排序
  3. Sort by their number of replies 按回复数量排序

Any help would be highly appreciated. 任何帮助将受到高度赞赏。

Thanks! 谢谢!

The having clause in the second query does not look correct. 第二个查询中的having子句看起来不正确。 In most dialects of SQL is would not be allowed without a group by . 在没有group by情况下,大多数SQL方言都是不允许group by I forget if MySQL t implicitly treats the whole query as an aggregation (returning one row) or if the having gets converted to a where . 我忘记了MySQL是否隐式将整个查询视为聚合(返回一行)或者将having转换为where In either case, you should be explicit and use where when there are no aggregations. 在任何一种情况下,您都应该明确并where没有聚合的地方使用。

You can just combine them by putting in the where clause. 你可以通过放入where子句来组合它们。 I would do it with a subquery, to make the variable definitions clearer: 我会用子查询来做,以使变量定义更清晰:

      SELECT p.title, p.num, p.status, p.distance,
             COUNT( p_replies.post_num)  AS count
      FROM posts_replies pr  INNER JOIN
           (select p.*,
                   ( 3959 * acos( cos( radians( 37 ) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians( -122 ) ) + sin( radians( 37 ) ) * sin( radians( lat ) ) ) ) AS distance
            from posts p
           ) p
           ON pr.post_num = p.num
      WHERE p.status = 1 AND
            p.category='uncategorized' and
            distance < 75
      GROUP BY p.num
      order by distance

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM