2015-12-30 89 views
1

如何合併這兩個查詢?我正在寫這個查詢的時間很艱難。兩個查詢在一個

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

只需使用派生表加入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) 
+0

感謝=),它的工作。我用了第二個。工作得很好==) –

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) 
+0

這工作太謝謝 –