MySQL子查询/相关查询

时间:2017-05-12 22:42:11

标签: php mysql subquery correlated-subquery

我正在构建用户统计信息页面并尝试正确显示统计信息,并希望得到一些帮助。

我有一个网站,为注册用户提供可下载的文件,我想跟踪下载次数以及每个用户下载该文件的次数以及他们下载的独特产品数量。

表:customer_statistics

| user |  product_id  |  file_download  |  date_accessed   |
------------------------------------------------------------
| tom  |  1104        |  mp3       |  2017-05-06 00:00:00  |
| tom  |  1048        |  video     |  2017-05-06 00:00:00  |
| tom  |  1048        |  video     |  2017-05-06 00:00:00  |
| tom  |  1048        |  video     |  2017-05-07 00:00:00  |
| tom  |  1048        |  video     |  2017-05-08 00:00:00  |
| tom  |  1010        |  video     |  2017-05-08 00:00:00  |
| tom  |  1077        |  video     |  2017-05-08 00:00:00  |
| sue  |  1749        |  photo     |  2017-05-09 00:00:00  |
| sue  |  1284        |  video     |  2017-05-09 00:00:00  |
| sue  |  1284        |  video     |  2017-05-09 00:00:00  |
| sue  |  1065        |  mp3       |  2017-05-09 00:00:00  |
| sue  |  1344        |  video     |  2017-05-10 00:00:00  |
| sue  |  2504        |  photo     |  2017-05-10 00:00:00  |

我会这样显示数据:

Name | Unique Mp3s | Unique Photos | Unique Videos | Total
----------------------------------------------------------
Tom  |    1        |    0          |    3          |  7
Sue  |    1        |    2          |    2          |  6

unique mp3s/photos/videos显示已下载的每种文件类型的唯一product_id数,而total显示为该特定用户添加的所有文件类型和事件的总量。

达到上述结果的最佳方法是什么?

提前感谢一大堆!

1 个答案:

答案 0 :(得分:2)

我会这样做,不需要子查询:

SELECT user AS `Name`,
  COUNT(DISTINCT CASE file_download WHEN 'mp3' THEN product_id END) AS `Unique Mp3s`
  COUNT(DISTINCT CASE file_download WHEN 'photo' THEN product_id END) AS `Unique Photos`
  COUNT(DISTINCT CASE file_download WHEN 'video' THEN product_id END) AS `Unique Videos`
  COUNT(DISTINCT product_id) AS `Total`
FROM customer_statistics
GROUP BY user;