简体   繁体   English

从另一个表插入数据作为外键

[英]Insert data from another table as a foreign key

There are two tables.有两张桌子。

Table 1表格1

           expenseID | description | generatedBy | notifyWho | frequencyGeneration
              1      | Advance Pay | Conductor   | Clerk     | Once a week
              2      | Contract Pay| Conductor   | Clerk     | Contract Period

enter image description here在此处输入图片说明

Table 2表 2

       divExpenseID |   divNo     | expenseID   |descriptions| date       | amount   | status
              1     |     1       |   1         | Clerk      | 2020-01-11 | 5000     | Pending
              2     |     1       |   1         | Clerk      | 2020-01-11 | 2000     | Active

enter image description here在此处输入图片说明

In this, I entered data to table 1 first, then I inserted data to table 2 except expenseID in table 2. I want to get data for expenseID using table 1.在此,我首先将数据输入到表 1,然后将数据插入到表 2,但表 2 中的费用 ID 除外。我想使用表 1 获取费用 ID 的数据。

As an example, when I insert data to divExpenseID, divNo, descriptions, date, amount, status expenseID should be updated automatically from table 1.例如,当我将数据插入divExpenseID 时,divNo、描述、日期、金额、状态费用 ID 应从表 1 中自动更新。

What is the query for that, is it better if I write only one query for above operation.什么是查询,如果我只为上述操作编写一个查询会更好。

The table 1 description tells that expenseID data type is char, but the datas you stored in expenseID are number.表 1 说明了费用 ID 数据类型是字符,但您存储在费用 ID 中的数据是数字。

I suggest you change the data type of expenseID to integer and use the AUTO_INCREMENT machanism for this field.我建议您将费用 ID 的数据类型更改为整数,并为此字段使用 AUTO_INCREMENT 机制。

After each the insertion of table 1 is completted then you can get the AUTO_INCREMENT id of the last row that has been inserted or updated in a table 1 by using在每次完成表 1 的插入后,您可以使用以下命令获取表 1 中已插入或更新的最后一行的 AUTO_INCREMENT id

SELECT LAST_INSERT_ID();选择 LAST_INSERT_ID();

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

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