我有两个包含多行的表。第一个称为comments
,具有以下结构:
user_id last_commented
........................
9239289 2017-11-06
4239245 2017-11-05
4239245 2017-11-03
6239223 2017-11-02
1123139 2017-11-04
第二个名为users
,具有以下结构:
user_id user_name user_status
.................................
9239289 First Name 0
4239245 First Name2 2
6239223 First Name3 1
1123139 First Name4 2
我需要一个查询,显示过去3天未添加评论且user_status
等于2的用户。
这是我目前的查询:
SELECT user_name FROM
(
SELECT MAX(last_commented) lastdate,user_id
FROM `comments`
GROUP BY user_id
) A
LEFT JOIN users
USING (user_id)
WHERE lastdate < ( DATE(NOW()) - INTERVAL 3 DAY )
AND user_status = 2
答案 0 :(得分:1)
例如,您可以使用NOT EXISTS
select u.*
from users u
where not exists (
select 1
from comments c
where c.user_id = u.user_id and last_commented > DATE(NOW()) - INTERVAL 3 DAY
) and user_status = 2
编辑:如果您想要上次用户在结果中登录后的天数,那么您可以使用以下方法:
select u.*, datediff(DATE(now()), comment.last_commented)
from users u
join (
select user_id, max(last_commented) last_commented
from comments
group by user_id
) comment on comment.user_id = u.user_id
where last_commented <= DATE(NOW()) - INTERVAL 3 DAY
此方法使用子查询查找最后一个注释日期,然后将其用于过滤和计算。
答案 1 :(得分:0)
您可以使用此查询。
SELECT MAX(last_commented) lastdate,user_id
FROM `comments`
where lastdate<DATE_SUB(NOW(), INTERVAL 3 day) and
user_status = 2
GROUP BY user_id