如何在限制之前使用子查询来计算结果?

时间:2017-06-15 11:29:56

标签: mysql sql subquery

我在同一个表上有两个具有相同where子句的查询。这样:

SELECT    qa.id, 
          qa.subject, 
          qa.category cat, 
          qa.keywords tags, 
          qa.body_html, 
          qa.amount, 
          qa.visibility, 
          qa.date_time, 
          COALESCE(u.reputation, 'N') reputation, 
          COALESCE(Concat(u.user_fname, ' ', u.user_lname), 'unknown') NAME, 
          COALESCE(u.avatar, 'anonymous.png') avatar, 
          ( 
                 SELECT COALESCE(Sum(vv.value),0) 
                 FROM   votes vv 
                 WHERE  qa.id = vv.post_id 
                 AND    15 = vv.table_code) AS total_votes, 
          ( 
                 SELECT COALESCE(Sum(vt.total_viewed),0) 
                 FROM   viewed_total vt 
                 WHERE  qa.id = vt.post_id 
                 AND    15 = vt.table_code limit 1) AS total_viewed 
FROM      qanda qa 
LEFT JOIN users u 
ON        qa.author_id = u.id 
AND       qa.visibility = 1 
WHERE     qa.type = 0
       OR amount IN ( :vals )
       OR date_time BETWEEN :s AND :e 
ORDER BY  $query_order
LIMIT     :j, 11;

而且:

SELECT COUNT(amount) paid_qs,
       COUNT(*) all_qs
FROM qanda qa
WHERE qa.type = 0
   OR amount IN ( :vals )
   OR date_time BETWEEN :s AND :e 

如你所见,第二个只是重要的事情。此外,where子句非常复杂,需要花费大量时间才能执行。

无论如何,我想结合这两个查询。像这样:

SELECT COUNT(amount) paid_qs, COUNT(*) all_qs, x.*
FROM (
    -- The first query should be here
) x
LIMIT :j, 11

但它并没有像预期的那样发挥作用。它返回一行。你知道我怎么能把上面这两个第一个查询结合起来呢?

0 个答案:

没有答案