我有表用户,评论,关注,提示,集合。我需要让所有在2016年1月注册并且至少完成一项活动的用户(至少有一次,至少有一次,至少创建一个集合,至少评论一次)在同一时期完成。这是我的问题:
SELECT distinct u.id FROM user u
where u.id in
(select distinct t.sender_id from tip t
WHERE t.date_added>='2016-01-01 00:00:00' AND t.date_added<'2016-02-01 00:00:00')
or u.id in
(select distinct c.user_id from collection c
WHERE c.date_created>='2016-01-01 00:00:00' AND c.date_created<'2016-02-01 00:00:00')
or u.id in
(select distinct cc.postedBy_id from comment cc
WHERE cc.date_posted>='2016-01-01 00:00:00' AND cc.date_posted<'2016-02-01 00:00:00')
or u.id in
(select distinct f.follower_id from follow f
WHERE f.follow_date>='2016-01-01' AND f.follow_date<'2016-02-01')
AND u.date_added>='2016-01-01 00:00:00' AND u.date_added<'2016-02-01 00:00:00'
t.date_added,c.date_created,cc.date_posted,f.follow_date,u.date_added - 具有DATETIME类型。 u.date_added - 注册日期
查询返回所有用户,而我需要u.date_added为2016年1月。我的查询有什么问题?
答案 0 :(得分:1)
编写查询时,日期条件仅适用于最后or
:
or
(
u.id in ()
AND
u.date_added>='...' AND u.date_added<'...'
)
(如mysql docs中所述,AND
优先于OR
)
您需要强制执行日期条件:
SELECT distinct u.id
FROM user u
where
(
u.id in (
select distinct t.sender_id from tip t
WHERE t.date_added>='2016-01-01 00:00:00' AND t.date_added<'2016-02-01 00:00:00'
)
or
u.id in (
select distinct c.user_id from collection c
WHERE c.date_created>='2016-01-01 00:00:00' AND c.date_created<'2016-02-01 00:00:00'
)
or
u.id in (
select distinct cc.postedBy_id from comment cc
WHERE cc.date_posted>='2016-01-01 00:00:00' AND cc.date_posted<'2016-02-01 00:00:00'
)
or
u.id in (
select distinct f.follower_id from follow f
WHERE f.follow_date>='2016-01-01' AND f.follow_date<'2016-02-01'
)
)
AND
u.date_added>='2016-01-01 00:00:00' AND u.date_added<'2016-02-01 00:00:00'
答案 1 :(得分:0)
您也可以使用两者之间进行更清晰的查询
SELECT distinct u.id FROM user u
where ( u.id in
(
select distinct t.sender_id from tip t
WHERE t.date_added BETWEEN '2016-01-01 00:00:00' AND '2016-02-01 00:00:00'
)
or u.id in
( select distinct c.user_id from collection c
WHERE c.date_created BETWEEN '2016-01-01 00:00:00' AND '2016-02-01 00:00:00'
)
or u.id in
( select distinct cc.postedBy_id from comment cc
WHERE cc.date_posted BETWEEN '2016-01-01 00:00:00' AND '2016-02-01 00:00:00'
)
or u.id in
(
select distinct f.follower_id from follow f
WHERE f.follow_date BETWEEN '2016-01-01' AND '2016-02-01'
) )
AND u.date_added BETWEEN '2016-01-01 00:00:00' AND '2016-02-01 00:00:00'