table:user
user_id int
desc varchar(255)
table:task
task_id int
user_id int
create_time datetime
我想得到desc =" sth"在今天& amp;昨天,所以我这样写了。
select u.user_id, today_task_count, yesterday_task_count
from user as u
inner join (
select user_id,
SUM(case when DATE(create_time) = CURDATE() then 1 else 0 end) as today_task_count
SUM(case when DATE(create_time) = CURDATE()-1 then 1 else 0 end) as yesterday_task_count
from task
group by user_id
) as t
On u.user_id = t.task_id
where u.desc = 'sth'
或
On u.user_id = t.task_id AND u.desc = 'sth'
但是他们都扫描了表格任务中的所有记录。 我该如何改进呢...... 我知道有一些问题像这样问过,但我仍然无法在我的场景中找到解决方案。
=========================更新===================== ======= 现在我使用jWeaver的anwer
select u.user_id,
SUM(case when DATE(create_time) = CURDATE() then 1 else 0 end) as today_task_count
SUM(case when DATE(create_time) = CURDATE()-1 then 1 else 0 end) as yesterday_task_count
from (SELECT * FROM user where desc = 'sth') as u for desc='sth'
inner join task as t
On u.user_id = t.task_id
group by u.user_id
对于desc条件它没问题,但它需要花费4秒钟,而我的第一个sql需要2秒才能完成,总和操作会有更多这样的痛苦吗?
答案 0 :(得分:0)
我认为这些SQL对你有用。
select u.user_id, count(*)
from user as u
inner join (
select user_id
from task
group by user_id
) as t
On u.user_id = t.task_id
AND u.desc = 'sth' and DATE(create_time) = CURDATE()
这些查询给出了今天的计数和昨天的计数
select user.user_id, today_task_count, yesterday_task_count
from
( SELECT * FROM user where desc = 'sth' ) as user
join
( select user_id,
SUM(case when DATE(create_time) = CURDATE() then 1 else 0 end) as today_task_count ,
SUM(case when DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)then 1 else 0 end) as yesterday_task_count
from task
group by user_id
) as task
On user.user_id = task.task_id
谢谢。
答案 1 :(得分:0)
好像你正在寻找这个..
select u.user_id, today_task_count
from (SELECT * FROM user where desc = 'sth') as u --- filter you table for desc='sth'
inner join (
select user_id,
SUM(case when DATE(create_time) = CURDATE() then 1 else 0 end) as today_task_count
from task
group by user_id
) as t
On u.user_id = t.task_id
<强> ===更新=== 强>
select u.user_id, SUM(case when DATE(create_time) = CURDATE() then 1 else 0 end) as today_task_count
from (SELECT * FROM user where desc = 'sth') as u --- filter you table for desc='sth'
inner join task as t
On u.user_id = t.task_id
group by u.user_id
答案 2 :(得分:0)
我不知道你为什么要尝试复杂的查询只是尝试这个,你会得到所需的结果:
select user.user_id,count(create_time) as today_task_count from task left join user on user.user_id=task.user_id
where create_time=current_date and description="sth" group by user.user_id;
答案 3 :(得分:0)
要包含昨天的点数和今天的点数,你可以尝试一下
select user.user_id,
count(case when task.create_time=current_date then 1 end) as today_task_count,
count(case when task.create_time=DATE_SUB(CURDATE(), INTERVAL 1 DAY) then 1 end) as yesterday_task_count
from task left join user on user.user_id=task.user_id
where user.description="sth" group by user.user_id;