MySQL 多个查询合并为一个

标签 mysql

我有一个 mysql 表,其中包含以下行:

id  |  event_type  |  occurance_date  |  ipaddress

我想获得天数、唯一访问次数和总访问次数/天。使用 2 个查询很容易做到这一点,但我只想进行一个查询。

所以我想 得到我能得到的日子

SELECT DISTINCT(occurance_date) as day FROM statistics WHERE event_type = 'visit' 
ORDER BY id DESC LIMIT 14;

获得独立访问/天

SELECT COUNT(DISTINCT(ipaddress)) as unique_visits FROM statistics WHERE occurance_date = '2011-05-11';

获取所有访问/天

SELECT COUNT(id) as total_visits FROM statistics WHERE occurance_date = '2011-05-11';

问题是我如何通过 unique_visits 和 total_visits 进行单个查询来返回所有天数。

(2011-05-11应该换成日期,只是举例)

欢迎任何建议。

谢谢。

最佳答案

select count(*) as total_visits, count(distinct(s1.ipaddress)) as unique_visits 
FROM statistics s1 
WHERE event_type = 'visit'
GROUP BY occurrence
ORDER BY unique_visits;

注释版:

首先我们做一个 SELECT 计数(所有行)

select count(*) as total_visits, 

加上不同 IP 地址的计数

count(distinct(s1.ipaddress)) as unique_visits 

根据统计,我添加了一个别名,但这只是出于习惯。不需要。

FROM statistics s1

请记住,您只需要具有 event_type“访问”的行。
您还需要一些相关信息,但您不想过滤掉这些信息,您只想将它​​们作为单独的项目显示在结果中。
所以我们唯一的过滤器event_type

WHERE event_type = 'visit'

我们按发生日期对结果进行分组,如果您省略这一行,您将只会看到一行。把它放回去看看区别。

GROUP BY occurrence

我们按访问次数对结果进行排序,除了我不想重写 count(distinct(s1.ipaddress)) 所以我写了别名 unique_visits ;这是允许的(甚至在 order by 子句中鼓励这样做。)

ORDER BY unique_visits;

链接:
Group by,不要管这个神话部分,只需阅读 group by 工作原理的描述:
http://dev.mysql.com/tech-resources/articles/debunking-group-by-myths.html
计数:http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html

关于MySQL 多个查询合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6242933/

相关文章:

php - MySQL Case when then 子句

java - 尝试在 select 语句中连接列时出现未找到列异常

php - 刷新页面创建的空行

MySQL:移动聚合/运行总计

php - 喜欢一个帖子的按钮实际上喜欢所有帖子

mysql - 我正在尝试使用 group by 和 order by 显示表中最后更新的记录

c# - Nhibernate可以从数据库自动生成映射文件吗?

mysql - 使用 REGEX 从 MySQL 中的 URL 中提取主机名

php - Eloquent 查询,检查电子邮件集合中是否有已批准每封电子邮件的批准者(当并非所有电子邮件都具有approval_status时)

php - mysql_fetch_array() : supplied argument is not a valid MySQL result resource in C:\wamp\www\mahesh\login\orderhistory. php 第 48 行