简体   繁体   中英

Combine two SQL Queries efficiently

I have two Queries:

1)

SELECT COUNT(*) AS total, COUNT(supporter) AS done FROM Supports;

2)

SELECT supporter, COUNT(supporter) AS amount FROM Supports 
GROUP BY supporter ORDER BY amount DESC LIMIT 1;

How can I efficiently combine them?

This is how the Table looks like:

+-----------------------------+
| id    | name    | supporter |
+-----------------------------+
|    1  | user1   |    sup1   |
|    2  | user1   |    sup2   |
|    3  | user1   |    NULL   |
|    4  | user2   |    sup1   |
|    5  | user2   |    sup3   |
+-----------------------------+

Since you want the total, you'll have to use a subquery to combine into one query. Include it in the FROM clause.

SELECT supporter, COUNT(supporter) AS amount, total, done 
FROM Supports,
    (SELECT COUNT(*) AS total, COUNT(supporter) AS done FROM Supports) totals
GROUP BY supporter
ORDER BY amount DESC
LIMIT 1;

I believe this is what you are looking for:

SELECT
  (SELECT COUNT(*) FROM Supports) as total,
  (SELECT COUNT(supporter) FROM Supports) as done,
  supporter, 
  COUNT(*) AS amount 
FROM Supports 
GROUP BY supporter 
ORDER BY amount;

Results looks like this: http://sqlfiddle.com/#!9/9e4ee/9

total  done  supporter   amount
5      4     sup3        1
5      4     sup2        1
5      4     NULL        1
5      4     sup1        2
SELECT  a.total, a.done, b.supporter, b.amount 
      ( SELECT  COUNT(*) AS total, 
                COUNT(supporter) AS done
            FROM  Supports 
      ) AS a
    JOIN  
      ( SELECT  supporter, 
                COUNT(supporter) AS amount
            FROM  Supports
            GROUP BY  supporter
            ORDER BY  amount DESC
            LIMIT  1 
      ) AS b;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM