简体   繁体   English

MySQL左连接并选择

[英]MySQL left join and select

I have two tables, mytable1 and mytable2. 我有两个表,mytable1和mytable2。 I get results from mytable1 and left join with 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

But I need to filter the results, so I will get only results if "mytable2.day2 mytable2.time2" is bigger than 2 days ago. 但是我需要过滤结果,因此,如果“ mytable2.day2 mytable2.time2”大于2天前,我将仅获得结果。 For example let datetime be "2014.03.27 21:00:00". 例如,让datetime为“ 2014.03.27 21:00:00”。 I will get results if mytable2 record is newer than "2014.03.27 21:00:00" 如果mytable2记录比“ 2014.03.27 21:00:00”新,我将得到结果

You can check sql fiddle here inital: http://sqlfiddle.com/#!2/a5364/2 您可以在此处检查sql小提琴: http ://sqlfiddle.com/#!2/a5364/2
My tryout: http://sqlfiddle.com/#!2/a5364/5 我的试用版: http ://sqlfiddle.com/#!2/a5364/5

Here is what the query will look like :- 这是查询的样子:-

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))

Use convert() to get the datetime and then use subdate() to find the date before 2 days. 使用convert()获取日期时间,然后使用subdate()查找2天之前的日期。

Verify it on the SQL Fiddle you provided. 在您提供的SQL Fiddle上进行验证。

The question is: if there are no records at all in mytable2 that match a record in mytable1 , do you still want to see the mytable1 record? 现在的问题是:如果没有记录,在所有的mytable2在匹配记录中mytable1 ,你还想看mytable1记录? If so, move the condition to the on clause: 如果是这样,请将条件移至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);

Otherwise, you can change the join to an inner join : 否则,您可以将联接更改为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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM