mysql - 哪个sql语句应该是正确的?

标签 mysql sql

我有一个 sql 问题。

web_requests: date, user_id, browser [chrome, firefox, ie], request_count

api_reques‍‍‍‍‍‍‍‌‍‌‍‌‌‌‌‌‍‌‌ts: date, user_id, devide_type [iphone, ipad, android-phone], request_count

目标:获取自年初以来每天在同一天在 iPhone 和 Web 上至少访问过一个页面的用户数

我在这里尝试了两种不同的sql,我想知道哪种更好?

1.

select w.date, sum(w.user_id) + count(a.user_id) as per-day-count
from 
(select * from web_requests where date >= '2017-01-01') as w

inner join

(select * from api_requets where device_type = 'iphone' and date >= '2017-01-01') as a
on w.date = a.date and w.user_id = a.user_id

2.

select date, count(distinct use‍‍‍‍‍‍‍‌‍‌‍‌‌‌‌‌‍‌‌r_id) as users
    from
    (
            select date, user_id
            from api_request
            where device_type = 'iphone' and date >= '2017-01-01' and request_count > 0
            UNION
            select date, user_id
            from web_request
            where date >= '2017-01-01' and request_count > 0
    ) a
    group by date

最佳答案

您可以像这样构建此查询。首先是获取 union 中的 count() 并获取结果表的 sum

select date, sum(ct) from (
    select count(1) as ct, user_id, date, 'web' as src from web_requests 
        where date >= '2017-01-01'
        group by date, user_id
    union
    select count(1) as ct, user_id, date, 'api' as src from api_requets 
        where device_type = 'iphone' and date >= '2017-01-01'
        group by date, user_id
) t1
group by t1.date

关于mysql - 哪个sql语句应该是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57846902/

相关文章:

sql - 如何使用加权子选择正确执行 SQL UPDATE?

c# - MySql 每天运行sql方法

mysql - 通过命令行将某些列从 csv 导入到 mysql

python - Django 创建不正确的 MySQL LIKE 语句

MySQL - 如何从 10 个表中获取信息

mysql - Full Outer Join "with"表不工作

sql - 如何在 Oracle 中转义单引号?

mysql - MYSQL中的LIMIT使用全索引扫描而不是范围扫描

php - 使用 php 从目录中随机选择图像并使用其文件名进行 mysql 查询

php - 进行更快的 MySQL PHP 查询