简体   繁体   English

如何在mysql中的where中使用COUNT()?

[英]How to use COUNT() with where in mysql?

I have tables pages (id, ...) and page_visits (id, page_id, is_subscribed)我有表格pages (id, ...)page_visits (id, page_id, is_subscribed)

The page_visits table now has about 2 million rows per one page_id. page_visits表现在每个 page_id 大约有 200 万行。

I need to create a query that will grab count of visits and subscriptions per one page.我需要创建一个查询来获取每页的访问和订阅数。 My query only grabs visits count now:我的查询现在只抓取访问次数:

SELECT page_id, COUNT(page_id) AS visits
FROM `page_visits`
WHERE `page_id` in (1, 2)
GROUP BY `page_id`

But how to add here an page_subscriptions column in result that will contains count of rows where is_subscriped = 1 per one page_id?但是如何在结果中添加一个page_subscriptions列,该列将包含每一个 page_id is_subscriped = 1的行数?

count ignores null s, so you could perform a count over a case expression: count忽略null s,因此您可以对case表达式执行count

SELECT   page_id, 
         COUNT(page_id) AS visits 
         COUNT(CASE is_subscribed WHEN 1 THEN 1 END) AS subscried_visits
FROM     page_visits
WHERE    page_id IN (1, 2) 
GROUP BY page_id

Just use count(*) and group by is_subscribed as well...只需使用count(*)并按is_subscribed分组...

select `page_id`, count(*) as visits, `is_subscribed` from `page_visits` group by `page_id`, `is_subscribed`

You will get 2 rows per page:每页您将获得 2 行:

  1. With count for subscribers有订阅人数
  2. With count for not subscribers非订阅者计数

count(*) does not ignore nulls count(*)不会忽略空值

I would recommend:我会推荐:

select page_id, count(*) visits, sum(is_subscribed) page_subscriptions
from page_visits
where page_id in (1, 2)
group by page_id

Rationale:理由:

  • I would expect page_id to not be nullable;我希望page_id不能为空; if so, count(*) is more efficient than count(page_id)如果是这样, count(*)count(page_id)更有效率

  • is_subscribed seems to be storing 0 / 1 values - so counting the number of 1 s is equivalent to suming the column; is_subscribed似乎存储0 / 1值 - 所以计算1的数量相当于对列求和; this is much more efficient than a conditional count这比条件计数有效得多

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

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