在我的Symfony2 / Doctrine2应用程序中,我有一个实体,分别是我的数据库中的一个表,我跟踪每个用户,如果他或她在指定的一天做了特定的操作。
我的表看起来像是这样,我们称之为track_user_action
:
+---------+------------+
| user_id | date |
+---------+------------+
| 1 | 2013-09-19 |
| 2 | 2013-09-19 |
| 1 | 2013-09-18 |
| 5 | 2013-09-18 |
| 8 | 2013-09-17 |
| 5 | 2013-09-17 |
+---------+------------+
我想检索一组行,其中显示最近30天,相应的工作日以及指定的用户是否在此表中有条目,例如适用于user_id = 1
的用户:
+------------+--------------+-----------------+
| date | weekday | has_done_action |
+------------+--------------+-----------------+
| 2013-09-20 | Friday | false |
| 2013-09-19 | Thursday | true |
| 2013-09-18 | Wednesday | true |
| ... | | |
| 2013-08-20 | Tuesday | false |
+------------+--------------+-----------------+
我可以想到一个LEFT JOIN
的日期表和我的track_user_action
。但是为日期创建一个特殊的表似乎毫无意义。 MySQL应该能够处理这些日子,不应该吗?
方法:
SELECT
# somehow retrieve last 30 days
date AS date,
DAYNAME(date) AS weekday,
IF ... THEN has_done_action = true ELSE has_done_action = false
# and according weekdays
LEFT JOIN track_user_action AS t
ON t.date = # date field from above
WHERE t.user_id = 1
ORDER BY # date field from above
DESC
LIMIT 0,30
我的问题:
YEAR()
或MONTH()
)? 答案 0 :(得分:1)
这是一个七天的工作查询语句(相应地调整查询30天):
SELECT
d.date AS date,
DAYNAME(d.date) AS weekday,
IF(t.user_id IS NOT NULL, 'true', 'false') AS has_done_action
FROM (
SELECT SUBDATE(CURDATE(), 1) AS date UNION
SELECT SUBDATE(CURDATE(), 2) AS date UNION
SELECT SUBDATE(CURDATE(), 3) AS date UNION
SELECT SUBDATE(CURDATE(), 4) AS date UNION
SELECT SUBDATE(CURDATE(), 5) AS date UNION
SELECT SUBDATE(CURDATE(), 6) AS date UNION
SELECT SUBDATE(CURDATE(), 7) AS date
) AS d
LEFT JOIN track_user_action t
ON t.date = d.date