插入,选择和where语句合并

时间:2015-07-28 06:34:19

标签: mysql sql sqlyog

如何根据表C中的条件将表A中的记录插入表B.

表A:

ID  Name   DateFrom   DateTo
1   Alex   22-7-2015  26-7-2015
2   Alice  21-8-2015  25-8-2015

表C:

ID  Quarter   DateFrom   DateTo
1   Quater 1  1-7-2015  31-7-2015
2   Quater 2  1-8-2015  31-8-2015

如果表A中的记录介于表C中的日期范围之间,则会插入新的表B.

赎回是表B

insert into redemption(staffID,staffName,department,pointsAccumulated,referrerID) 
select referrerStaffID,referrerName,referrerDepartment,SUM(points),activeDirectoryID 
FROM referral 
WHERE NOT EXISTS (select * from redemption1 where referrerID=activeDirectoryID) group by activeDirectoryID;

4 个答案:

答案 0 :(得分:3)

试试这个

Insert into tableB(Id,name,datefrom,dateto)
select t1.Id,t1.name,t1.datefrom,t1.dateto from tableA as t1 
inner join tableC as t2 on t1.id=t2.id 
where 
t1.datefrom between t2.datefrom and t2.dateto or 
t1.dateto between t2.datefrom and t2.dateto

答案 1 :(得分:1)

我会使用带有WHERE NOT EXISTS..构造

的相关子查询
insert into 
redemption(
            staffID,
            staffName,
            department,
            pointsAccumulated,
            referrerID
          ) 
select 
referrerStaffID,
referrerName,
referrerDepartment,
SUM(points),
activeDirectoryID 
FROM referral  r
WHERE NOT EXISTS (
                    select 1 from redemption1 r1 where 
                    r1.referrerID=r1.activeDirectoryID 
                    and (r.datefrom between r1.datefrom and r1.dateto or 
                         r.dateto between r1.datefrom and r1.dateto) 
                 )
group by r.referrerStaffID,r.referrerName,r.referrerDepartment,r.activeDirectoryID;

答案 2 :(得分:1)

您可以使用以下查询

insert into tableB(id,name,datefrom,dateto)
select A.id,A.name,A.datefrom,A.dateto from tableA A join tableC C 
                       on A.id=C.id 
      where TO_DATE(A.datefrom,'DD-mm-yyyy') 
            between TO_DATE(C.datefrom,'DD-mm-yyyy') and TO_DATE(c.dateto,'DD-mm-yyyy')
      and TO_DATE(A.dateto,'DD-mm-yyyy') 
            between TO_DATE(C.datefrom,'DD-mm-yyyy') and TO_DATE(c.dateto,'DD-mm-yyyy')

请在此处查看答案SQL Fiddle

答案 3 :(得分:1)

我认为其他人已经回答了这个问题,但我想补充一下,如果表A和表B的架构是相同的,你也可以这样做:

Insert into tableB 
Select * from tableA
Where....

不再重复where子句,因为它已经回答了。