这是我当前的数据库:
TABLE profileData
+---------------------------+
| profileID | name |
+----+----------------------+
| 1 | Stackoverflow |
| 2 | Stackexchange |
| 3 | Askubuntu |
+-----------+---------------+
TABLE stats
+----+-----------+------------------------------+
| id | profileID | sCount | ts |
+----+-----------+--------+---------------------+
| 1 | 1 | 1 | 2013-10-04 00:00:01 |
| 2 | 2 | 5 | 2013-10-04 00:00:01 |
| 3 | 3 | 8 | 2013-10-04 00:00:01 |
| 4 | 1 | 10 | 2013-10-05 00:00:01 |
| 5 | 2 | 50 | 2013-10-05 00:00:01 |
| 6 | 1 | 100 | 2013-10-06 00:00:01 |
| 7 | 2 | 500 | 2013-10-06 00:00:01 |
| 8 | 1 | 101 | 2013-10-06 13:00:01 |
| 9 | 2 | 501 | 2013-10-06 19:00:01 |
| 10 | 3 | 17 | 2013-10-06 05:00:01 |
| 11 | 1 | 100 | 2013-10-09 00:00:01 |
| 12 | 2 | 500 | 2013-10-09 00:00:01 |
+----+-----------+------- +---------------------+
TABLE users
+--------+-----------+
| userID | profileID |
+--------------------+
| 1337 | 1 |
| 1337 | 2 |
+--------+-----------+
我需要的是以下内容:
从“用户”表中选择所有配置文件,并从“统计”表中获取这些配置文件过去 7 天的名称+每天的最后一个条目。所以,预期的结果是
+---------------+--------+---------------------+
| name | sCount | ts |
+---------------+--------+---------------------+
| Stackoverflow | 1 | 2013-10-04 00:00:01 |
| Stackexchange | 5 | 2013-10-04 00:00:01 |
| Stackoverflow | 10 | 2013-10-05 00:00:01 |
| Stackexchange | 50 | 2013-10-05 00:00:01 |
| Stackoverflow | 101 | 2013-10-06 13:00:01 |
| Stackexchange | 501 | 2013-10-06 19:00:01 |
| Stackoverflow | 100 | 2013-10-09 00:00:01 |
| Stackexchange | 500 | 2013-10-09 00:00:01 |
+---------------+--------+---------------------+
我最终得到了这样的声明:
SELECT
profileData.name,
stats.scount,
stats.ts
FROM
users
INNER JOIN profiles ON
users.profileID = profiles.profileID
INNER JOIN
(
SELECT t1.profileID, t1.sCount, t1.ts
FROM stats t1
INNER JOIN (
SELECT MAX(ts) maxi
FROM stats
GROUP BY DATE(ts)
) a2 ON t1.ts = a2.maxi) stats ON
users.profileID = stats.profileID
WHERE
users.userID = 1337 AND DATE(stats.ts) >= DATE(DATE_SUB(NOW(), INTERVAL 7 DAY))
ORDER BY users.userID, stats.ts
这部分工作。然而,这个声明似乎是一种矫枉过正,它不再起作用了。
我也尝试过选择MAX(ts)
。那行得通,但结果不包含对应的sCount
值。
所以,我正在寻找我的问题的解决方案,我希望任何人都可以帮助我。
哦,如果可能的话,它必须是一个纯 SQL 解决方案。