MySQL离开了加入并选择

时间:2014-03-27 20:56:08

标签: mysql sql

我有两个表,mytable1和mytable2。我从mytable1获得结果,并使用mytable2离开加入。

CREATE TABLE mytable1 
    ( userid int, 
     type int, 
     datetime1 DATETIME );
CREATE TABLE mytable2
    ( userid int,
     name varchar(20),
     day2 DATE,
     time2 TIME );

SELECT x.*, d.name, d.day2, d.time2
  FROM ( SELECT * FROM mytable1 WHERE TYPE=1 ORDER BY userid ASC LIMIT 0,50) x
   LEFT JOIN mytable2 d
   ON x.userid = d.userid

但是我需要过滤结果,所以如果" mytable2.day2 mytable2.time2"我将只得到结果。大于2天前。例如,让datetime为" 2014.03.27 21:00:00"。如果mytable2记录比" 2014.03.27 21:00:00"

更新,我会得到结果

你可以在这里查看sql fiddle:http://sqlfiddle.com/#!2/a5364/2
我的试用版:http://sqlfiddle.com/#!2/a5364/5

2 个答案:

答案 0 :(得分:0)

以下是查询的外观: -

select x.*, d.name, d.day2, d.time2
from ( SELECT * FROM mytable1 WHERE type=1 ORDER BY userid ASC LIMIT 0,50) x
left join mytable2 d
on x.userid = d.userid
where ( convert(CONCAT(d.day2,' ',d.time2),datetime) >= SUBDATE(curdate(),INTERVAL 2 DAY))

使用convert()获取日期时间,然后使用subdate()查找2天之前的日期。

在您提供的SQL Fiddle上验证它。

答案 1 :(得分:0)

问题是:如果mytable2中没有与mytable1中的记录匹配的记录,您是否还想查看mytable1记录?如果是,请将条件移至on子句:

  select x.*, d.name, d.day2, d.time2
  from (SELECT *
        FROM mytable1
        WHERE type = 1
        ORDER BY userid ASC
        LIMIT 0,  50
       ) x left join
       mytable2 d
       on x.userid = d.userid and
          (d.day2 + d.time2) >= DATE_SUB(NOW(), INTERVAL 2 DAY);

否则,您可以将联接更改为inner join

  select x.*, d.name, d.day2, d.time2
  from (SELECT *
        FROM mytable1
        WHERE type = 1
        ORDER BY userid ASC
        LIMIT 0, 50
       ) x join
       mytable2 d
       on x.userid = d.userid
  where (d.day2 + d.time2) >= DATE_SUB(NOW(), INTERVAL 2 DAY);