简体   繁体   English

根据另一个表中的日期选择日期范围内的行。 (MYSQL)

[英]Selecting rows that are within a date range based on a date from another table. (MYSQL)

I have two tables, which share a key that link the two.我有两个表,它们共享一个链接两者的键。 Table A has a date column (of the format MM\/DD\/YYYY), and table B has a date field of the format (YYYY-MM-DD HH:MM:SS).表 A 有一个日期列(格式为 MM\/DD\/YYYY),表 B 有一个格式为 (YYYY-MM-DD HH:MM:SS) 的日期字段。

What I need to do is select all those in table B, that have a key matching table A AND a date field within 30 days of the date field found in table A.我需要做的是选择表 B 中所有那些在表 A 中找到的日期字段的 30 天内有一个键匹配表 A 和一个日期字段的人。

Edit: Both variables are varchars, here is what I currently have (error from using alias formattedEffective in a join).编辑:这两个变量都是 varchars,这是我目前拥有的(在连接中使用别名 formattedEffective 时出错)。 I think the below would work, if I could use aliases in that way.如果我可以以这种方式使用别名,我认为下面的方法会起作用。

select *, 
DATE_FORMAT(STR_TO_DATE(`Eff_date`, '%m/%d/%Y'), '%Y-%m-%d') as formattedEffective 
from `customers`
    right join `dispatch` on `customers`.`Member_no` = `dispatch`.`Member_no` 
        AND `dispatch`.`sortdate` > formattedEffective 
        AND `dispatch`.`sortdate` < DATE_ADD(formattedEffective,INTERVAL 30 DAY)

What the community is asking for is the ability to create a scenario to give a definitive answer to your question (create table statements, sample data, etc..).社区所要求的是能够创建一个场景来为您的问题提供明确的答案(创建表语句、示例数据等)。 The approach below is speculation.下面的方法是推测。

The assumption the query makes is eff_date is a string and sortdate is stored as a MySQL date (ie, date, datetime, timestamp).查询做出的假设是 eff_date 是一个字符串,而 sortdate 存储为 MySQL 日期(即日期、日期时间、时间戳)。

select d.*,
       str_to_date(c.eff_date, '%m/%d/%Y') ) as formattedEffective 
  from customer c
  join dispatch d on (   d.member_no = c.member_no
                     and d.sortdate between str_to_date(c.eff_date, '%m/%d/%Y')
                                        and str_to_date(c.eff_date, '%m/%d/%Y')  + interval 30 day );

In case the above answer does not work, move the matching range to where condition.如果上述答案不起作用,请将匹配范围移动到where条件。

select d.*,
       str_to_date(c.eff_date, '%m/%d/%Y') ) as formattedEffective 
  from customer c
  join dispatch d on (   d.member_no = c.member_no) 
  where d.sortdate between str_to_date(c.eff_date, '%m/%d/%Y')
                                        and str_to_date(c.eff_date, '%m/%d/%Y')  + interval 30 day );

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

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