MySQL-将两个具有相同列值的表合并,并比较开始日期和结束日期

时间:2018-09-26 06:59:11

标签: mysql database

嗨,我正在尝试合并两个具有相同列值为t1的表。 和t2.id然后合并时,我想显示status = Active的所有地址,该地址与Bid = 2001的地址相同,并且在Bid =“ 2001”的开始日期和结束日期范围内发生冲突。我认为我的查询是一个问题,我是初学者,因此,任何建议都将非常感谢。

tblAddress:

id (VARCHAR(255))           
Address (LONGTEXT)   
startdate (LONGTEXT)   
enddate   (LONGTEXT) 
Bid   (LONGTEXT) 

tblbook:

id (VARCHAR(255))           
STATUS (LONGTEXT)   


tblAddress

id      Address        startdate      enddate                 Bid
x12es1  Place1       2018-08-27       2018-08-30               2001
x12fs2  Place1       2018-08-28       2018-08-30               2002
x1sd13  Place1       2018-08-27       2018-09-29              2003 
x12f14  Place4       2018-09-17       2018-09-18               2004


tblbook

id        Status
2001      Active
2002      Active
2003      Active
2004      Active

My output doesnt display anything

Bid         id           Status            startdate        enddate     Address

Desired Output
will only display those who has a conflict with bid 2001 start date and endate

Bid           id            Status                      startdate                enddate          Address
2002          2002            Active                      2018-08-28          2018-08-30         Place1
2003          2003            Active                      2018-08-27           2018-09-29        Place1    

Query

SELECT t2.Bid,t1.id,t1.Status,t2.startdate,t2.endddate,t2.Address
 FROM tblbook t1  INNER JOIN  tblAddress t2
ON t1.id =t2.Bid
WHEREt1.Status = 'Active' AND   
@check_period_start BETWEEN STR_TO_DATE(t2.startdate,'%Y-%m-%d')AND STR_TO_DATE(t2.enddate,'%Y-%m-%d') 
  AND @check_period_end BETWEEN STR_TO_DATE(t2.startdate,'%Y-%m-%d')AND STR_TO_DATE(t2.enddate,'%Y-%m-%d')  

2 个答案:

答案 0 :(得分:1)

您还应该为@check_period_start和@check_period_end建立适当的日期

private static bool IsValid(string s)
{
    return s.Split(new []{',','-'}).All(x => int.TryParse(x, out var v) && v >= 1 && v <= 150);
}

答案 1 :(得分:1)

尝试一下:

select * from tblAddress t
where exists(select 1 from tblbook
             where id = t.bid and status = 'Active')
and exists(select 1 from tblAddress
           where bid = 2001 and
           t.startdate < enddate and
           t.enddate > startdate)
and bid <> 2001

您需要在日期列中使用正确的数据类型!我的意思是应该是date

Demo