How can I use sub query to count the result before limiting?

馋奶兔 提交于 2020-01-26 01:28:05

问题


I have two queries on the same table which have identical where clause. This:

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;

And this:

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 

As you see, the second one just counts something. Also, where clause is really complex which takes lots of time to be executed.

Anyway, I want to combine those two queries. Something like this:

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

But it doesn't work as expected. It returns one row. Do you know how can I combine those two first queries above?

来源:https://stackoverflow.com/questions/44566376/how-can-i-use-sub-query-to-count-the-result-before-limiting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!