简体   繁体   中英

how to create a foreign key for a serial data type column in sql

I have a situation where I need to create a foreign key for serial type column in mysql.

And also I would like to know, whether it is a good practise/standard to define a foreign key for a serial type column (which is a primary key)

Table 1 :

txn_id SERIAL,
txn_status integer

Table 2 :

txn_id integer foreign key (for table1.txn_id)
txn_error_code integer

Since SERIAL is an alias for BIGINT UNSIGNED , you can use the code as below.

CREATE TABLE IF NOT EXISTS Table2(
txn_id BIGINT UNSIGNED,
txn_error_code integer,
FOREIGN KEY (txn_id) REFERENCES Table1 (txn_id))

You can of course create a foreign key for a serial type column, but the problem would arise if there is no link between the two tables. Just remember that a foreign key can be implemented only when there are corresponding values to that value in the two tables. As the serial of the same item may differ in the second or referenced table. You will have to pay extra attention to match the serial of the items in the two table or else the data will be lost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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