我的查询应计算日期列中的日期:
我的查询如下:
select u.user_id, count(m.theater_release_date < CURDATE()) as 'no. upcoming',
count(m.theater_release_date BETWEEN CURDATE() - INTERVAL 90 DAY AND CURDATE()) as 'no.
currently', count(m.theater_release_date < CURDATE() - INTERVAL 90 DAY) as 'no. older'
from users u join movie m on m.movie_id = u.movie_id
group by u.user_id;
我在日期列中找回相同的数字,这显然表明我的查询没用。
---------+--------------+-----------------+------------+
| user_id | no. upcoming | no. currently | no. older |
+---------+--------------+-----------------+------------+
| 1 | 197 | 197 | 197 |
| 1929 | 11 | 11 | 11 |
| 2161 | 18 | 18 | 18 |
| 4385 | 10 | 10 | 10 |
| 4897 | 3 | 3 | 3 |
| 5737 | 6 | 6 | 6 |
| 6177 | 4 | 4 | 4 |
| 6289 | 12 | 12 | 12 |
感谢Fabricator,你的查询带回了与我非常相似的结果,现在只有中间列全部为0。
+---------+--------------+---------------+-----------+
| user_id | no. upcoming | no. currently | no. older |
+---------+--------------+---------------+-----------+
| 1 | 197 | 0 | 197 |
| 1929 | 11 | 0 | 11 |
| 2161 | 18 | 0 | 18 |
| 4385 | 10 | 0 | 10 |
| 4897 | 3 | 0 | 3 |
| 5737 | 6 | 0 | 6 |
| 6177 | 4 | 0 | 4 |
| 6289 | 12 | 0 | 12 |
| 7353 | 6 | 0 | 6 |
| 7417 | 1 | 0 | 1 |
| 7465 | 11 | 0 | 11 |
答案 0 :(得分:1)
MySQL将布尔值视为整数,其中true为1,false为0.因此,您只需将count()
替换为sum()
:
select u.user_id, sum(m.theater_release_date < CURDATE()) as `no. upcoming`,
sum(m.theater_release_date BETWEEN CURDATE() - INTERVAL 90 DAY AND CURDATE()) as `no. currently`,
sum(m.theater_release_date < CURDATE() - INTERVAL 90 DAY) as `no. older`
from users u join
movie m
on m.movie_id = u.movie_id
group by u.user_id;
注意:您应该仅对字符串和日期常量使用单引号。使用反引号(在MySQL中)来转义列别名。
答案 1 :(得分:0)
MySQL也会计算错误值,而是使用sum(if(condition,1,0))
,如下所示:
select u.user_id, sum(if(m.theater_release_date < CURDATE(),1,0)) as 'no. upcoming',
sum(if(m.theater_release_date BETWEEN CURDATE() - INTERVAL 90 DAY AND CURDATE(),1,0)) as 'no.
currently', sum(if(m.theater_release_date < CURDATE() - INTERVAL 90 DAY,1,0)) as 'no. older'
from users u join movie m on m.movie_id = u.movie_id
group by u.user_id;