SQL - 根据多个条件插入数据

时间:2015-06-15 11:03:12

标签: mysql sql insert

我正在尝试根据另一个表中的数据插入包含不同数据的行数。

情景:

我有列tbl1_actiontbl1_actiondate。 我想在tbl2中搜索tbl2_reviewdatetbl2_destroydate中的数据。如果tbl2_reviewdate中有数据,那么我需要tbl1_action = 'review'tbl1_actiondate = tbl2_reviewdate。如果tbl2_destroydate中有数据,我需要另一个tbl1_action = 'destroy'tbl1_actiondate = tbl2_destroydate.

总结所有可能的情况:

If tbl2_ReviewDate IS NULL AND
   tbl2_DestroyDate IS NULL

使用action和actiondate = NULL

将一条记录插入tbl1
   tbl2_ReviewDate IS NOT NULL AND
   tbl2_DestroyDate IS NULL
Insert one row with tbl1_action = 'Review' and tbl1_actiondate = tbl2_reviewdate

   tbl2_ IS NULL AND
   tbl2_DestroyDate IS NOT NULL
Insert one row with tbl1_action = 'Destroy' and tbl1_actiondate = tbl2_destroydate

   tbl2_ReviewDate IS NOT NULL AND
   tbl2_DestroyDate IS NOT NULL
Insert two rows; One with tbl1_action = 'Destroy' and tbl1_actiondate = tbl2_destroydate and one with tbl1_action = 'Review' and tbl1_actiondate = tbl2_reviewdate.

是否可以在一个脚本中执行此操作?最好的方法是什么?

谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

insert into table1(action, date)
    select 'Review', ActionDate
    from tbl2
    where tbl2.ReviewDate IS NOT NULL
    union all
    select 'Destroy', DestroyDate
    from tbl2
    where tbl2.DestroyDate IS NOT NULL;

您也可以将其作为两个单独的insert语句执行此操作。