我有一个表格
| FormId | FormName | ParentLawId | StartDate | Frequency |
|--------|----------|-------------|------------|-----------|
| 1 | FormA | 21 | 2017-11-06 | Monthly |
| 2 | FormB | 22 | 2016-12-06 | Yearly |
| 3 | FormC | 24 | 2015-06-08 | Quaterly |
| 4 | FormD | 24 | 2018-02-11 | Monthly |
我有另一个日历表
| CalendarId | LawId | StartDate | Frequency | FormId |
|------------|-------|------------|-----------|--------|
| 1 | 21 | 2017-11-06 | Monthly | 1 |
| 2 | 24 | 2015-06-08 | Quaterly | 3 |
我想在 CalendarTable 中为在 CalendarTable 中没有相应记录的表单(在 FormTable 中)插入记录。
比如最终的CalendarTable应该是
| CalendarId | LawId | StartDate | Frequency | FormId |
|------------|-------|------------|-----------|--------|
| 1 | 21 | 2017-11-06 | Monthly | 1 |
| 2 | 24 | 2015-06-08 | Quaterly | 3 |
| 3 | 22 | 2016-12-06 | Yearly | 2 |
| 4 | 24 | 2018-02-11 | Monthly | 4 |
因此,在 CalendarTable 中生成了 2 条新记录,对应于 FormId(FormTable) 列,并且 CalendarTable 中其余列的值应该与 FormTable 中相应列中的值相同
两个表的模式的SQL Fiddle
最佳答案
在你的存储过程中使用这个查询
注意:保持日历id为自增
insert into CalendarTable(LawId, StartDate, Frequency, FormId)
select ParentLawId,StartDate,Frequency,FormId
from FormTable where formid not in(select formid from CalendarTable);
关于mysql - 根据另一个表中的记录在一个表中插入记录的 SQL 过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53718151/