简体   繁体   English

如何同时查询和计数以及不同计数?

[英]How to query and count and count distinct at the same time?

SELECT * FROM UserTable limit 100 ORDER BY userID ASC offset 0 ROWS;
SELECT COUNT(*) FROM UserTable;
SELECT COUNT(DISTINCT email) FROM UserTable;

How to combine it all into one query? 如何将它们全部组合成一个查询?

Expected output should be something like 预期的输出应该是这样的

totalCount    distinctCount    userID    email ...
100000        1000             1         qwerty@qwerty.com
100000        1000             2         qwerty@qwerty.com
100000        1000             3         abc.abc.com
...

You could use a cross join on the count subquery 您可以在count子查询上使用交叉联接

  SELECT t.totalCount, t.distinctCount, UserTable.* 
  FROM UserTable 
  cross join (
    SELECT COUNT(*)  totalCount, COUNT(DISTINCT email) as distinctCount
    FROM UserTable
  ) t 
  ORDER BY userID ASC limit 100 

here you are: 这个给你:

    select 
(select count(*) from UserTable a) as count,
(select count(DISTINCT quarter) from UserTable b) as distinctCount,
c.* from UserTable as c order by userID ASC limit 100;

You're looking for a group by: 您正在寻找一个分组依据:

Try following query: 尝试以下查询:

SELECT * FROM UserTable limit 100 ORDER BY userID ASC offset 0 ROWS GROUP BY email SELECT * FROM UserTable限制100 ORDER BY userID ASC偏移量0 ROWS GROUP BY电子邮件

You could achieve it using subquery Join in MySQL: 您可以使用MySQL中的子查询Join实现此目的:

SELECT UserTable.*, tc.totalCount, dc.distinctCount
FROM UserTable 
JOIN (
    SELECT COUNT(*) as totalCount
    FROM UserTable
) tc
JOIN (
    SELECT COUNT(DISTINCT email) as distinctCunt
    FROM UserTable
) dc
ORDER BY userID ASC 
LIMIT 100 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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