两个查询合二为一

时间:2015-12-30 23:44:08

标签: sql postgresql

如何合并这两个查询?我正在编写这个查询。

1)

SELECT question_id, name, question_text FROM questions 
 WHERE ST_Intersects(ST_Buffer(ST_GeomFromText('POINT(-99.254512 19.347091)',
 4326)::geography, 1000)::geometry, the_geom)

2)

select q.question_id, COUNT(qa.question_id) as answer_count
from    questions q
left join question_answers qa
on qa.question_id = q.question_id
group by q.question_id

(我在SQL中是一个完整的菜鸟。)

有没有办法做到这一点:

SELECT 
(COUNT(qa.question_id) as answer_count
from    questions q
left join question_answers qa
on qa.question_id = q.question_id
group by q.question_id),

question_id, name, question_text FROM questions 
WHERE ST_Intersects(ST_Buffer(ST_GeomFromText('POINT(-99.254512 19.347091)',
4326)::geography, 1000)::geometry, the_geom)

2 个答案:

答案 0 :(得分:2)

只需使用由question_id加入的派生表,因为两个查询共享questions作为表源(调整WHERE子句函数以在任何列字段中包含t1表别名) :

SELECT t1.question_id, t1.name, t1.question_text, t2.answer_count    
FROM    
    (SELECT question_id, name, question_text 
     FROM questions 
     WHERE ST_Intersects(ST_Buffer(ST_GeomFromText('POINT(-99.254512 19.347091)',
           4326)::geography, 1000)::geometry, the_geom)) AS t1    
INNER JOIN    
    (SELECT q.question_id, COUNT(qa.question_id) as answer_count
     FROM  questions q
     LEFT JOIN question_answers qa 
     ON qa.question_id = q.question_id
     GROUP BY q.question_id) AS t2    
ON t1.question_id = t2.question_id

或者,您可以使用聚合子查询转到建议的路由,再次通过question_id匹配内部和外部查询(如上所述调整WHERE子句函数以在任何列上包含main表别名字段):

SELECT main.question_id, main.name, main.question_text,
       (SELECT COUNT(qa.question_id)
        FROM  questions q
        LEFT JOIN question_answers qa 
        ON qa.question_id = q.question_id
        WHERE q.question_id = main.question_id
        GROUP BY q.question_id) as answer_count 
FROM questions AS main
WHERE ST_Intersects(ST_Buffer(ST_GeomFromText('POINT(-99.254512 19.347091)',
       4326)::geography, 1000)::geometry, the_geom)

答案 1 :(得分:2)

这可以简化:

select q.question_id, COUNT(qa.question_id) as answer_count
from    questions q
left join question_answers qa
on qa.question_id = q.question_id
group by q.question_id

为:

select qa.question_id, COUNT(qa.question_id) as answer_count
from    question_answers qa
group by qa.question_id

然后可能会以这种方式添加到其他查询中

SELECT q.question_id, q.name, q.question_text, COALESCE(qac.answer_count,0) as answer_count
FROM questions q
LEFT JOIN (
            select qa.question_id, COUNT(qa.question_id) as answer_count
            from question_answers qa
            group by qa.question_id
          ) qac on q.question_id = qac.question_id
WHERE ST_Intersects(ST_Buffer(ST_GeomFromText('POINT(-99.254512 19.347091)',
 4326)::geography, 1000)::geometry, the_geom)