如何在MySQL中的多个表中的特定日期内检索数据

时间:2014-08-05 09:37:16

标签: mysql sql join date-range

我想获取那些未在指定日期范围内执行action_id 110的用户

日期范围 从 - 2014-04-01 至 - 2014-08-08

tbl_user

userid  name    email                       db_add_date
1       steve   stevemartin144@gmail.com    2014-04-08 01:11:37
2       mark    mark04@gmail.com            2014-07-18 07:10:01
3       nelson  nel02@yahoo.com             2014-05-28 14:02:04
4       andrew  amaria@gmail.com            2014-01-12 10:42:39
5       himou   hil_man@gmail.com           2014-03-22 23:32:04

tbl_points

id  userid  action_id  points
1   2       110        10
2   1       100        45
3   1       110        10
4   4       104        25
5   3       100        28

结果将是

-------------
name    email
-------------
nelson  nel02@yahoo.com
andrew  amaria@gmail.com
himou   hil_man@gmail.com

5 个答案:

答案 0 :(得分:3)

DATETIMEtbl_points,(而不是)/(以及)tbl_action上应该有一个tbl_user,但是使用 SELECT t.name, t.email FROM tbl_user tu LEFT JOIN tbl_points tp ON tu.userid = tp.userid AND tp.action_id = 110 WHERE tu.db_add_date NOT BETWEEN '2014-04-01' AND '2014-08-08' AND tp.id IS NULL 你目前的结构:

{{1}}

答案 1 :(得分:2)

select u.name,u.email from tbl_user u
left join tbl_points p on p.usrid=u.userid and p.action_id=110
where u.db_add_date between '2014-04-01' and '2014-08-08' 
and p.id is null

答案 2 :(得分:0)

我认为这会对你有帮助

Select u.name, u.email from tbl_user u, tbl_points p 
where p.action_id!=110
AND u.db_add_date BETWEEN '2014-04-01' AND '2014-08-08'
group by u.userid;

,查询的结果将是

NAME    EMAIL
steve   stevemartin144@gmail.com
mark    mark04@gmail.com
nelson  nel02@yahoo.com

您可以查看此SQL Fiddle

答案 3 :(得分:-1)

类似的东西:

SELECT * FROM tbl_user A
INNER JOIN tbl_points B ON A.userid   = B.userid  
WHERE (A.db_add_date BETWEEN ' 2014-04-01' AND '2014-08-08') 
AND (B.action_id <> 110)

答案 4 :(得分:-3)

select tu.name,tu.email from tbl_users tu
inner join tbl_points tp on tu.user_id=tp.user_id
where date(tu.db_add_date) between 2014-04-01 and 2014-08-08
and tp.action_id <> 110