如何减少子查询中的JOIN?

时间:2019-04-08 10:21:32

标签: mysql sql

这是我当前的查询:

SELECT q.type,
      q.author_id author,
      q.deleted,
      q.deleter_id,
      COUNT(DISTINCT a.id) answers_num,
      COUNT(DISTINCT v.id) votes_num,
FROM qanda q
LEFT  JOIN qanda a ON q.id = a.related
LEFT  JOIN votes v on q.id = v.post_id
WHERE q.id = ?

效果很好。我只需要在EXISTS语句中再添加一件事(由SELECT返回一个布尔值)。这个:

EXISTS (SELECT a.id, sum(vot.value) total_votes
        FROM qanda q
        LEFT JOIN qanda a on q.id = a.related
        LEFT JOIN votes vot ON a.id = vot.post_id
        WHERE q.type = 0         -- this is a question
          AND a.related = 1315   -- getting answers
        GROUP BY a.id
        HAVING total_votes
        ORDER BY total_votes DESC
        LIMIT1
) as HasAUpvotedAnswer

好的,它也很好用。但我担心性能。如您所见,以上两个查询中的JOIN(都是最终合并的)是相似的。如何使它们更优化?

换句话说,如何在最佳情况下结合以上两个查询?

1 个答案:

答案 0 :(得分:1)

查看您的代码可能是y可以使用条件查询求和的单个查询

SELECT q.type,
      q.author_id author,
      q.deleted,
      q.deleter_id,
      COUNT(DISTINCT a.id) answers_num,
      COUNT(DISTINCT v.id) votes_num,
      IF (SUM(
        CASE WHEN q.type  = 0 AND a.related = 1315
          THEN v.value  else  0 END) > 0,1,0) 
      HasAUpvotedAnswer
FROM qanda q
LEFT  JOIN qanda a ON q.id = a.related
LEFT  JOIN votes v on q.id = v.post_id
WHERE q.id = ?