📅  最后修改于: 2023-12-03 15:05:17.089000             🧑  作者: Mango
In SQL, creating tables with references is a common task. While it is often assumed that the reference must be the primary key of the referenced table, this is not always the case. This tutorial will explain how to create tables with references that are not the primary key of the referenced table, and provide examples to illustrate these concepts.
In SQL, a reference is a relationship between two tables, where a column or set of columns in one table refers to a column or set of columns in another table. This relationship is often used to enforce referential integrity, meaning that the values in the referencing column(s) must match the values in the referenced column(s).
To create a table with a reference to another table in SQL, use the CREATE TABLE
statement with the REFERENCES
keyword. The syntax for creating a table with a reference is as follows:
CREATE TABLE table_name (
column1 datatype PRIMARY KEY,
column2 datatype REFERENCES referenced_table_name (referenced_column),
column3 datatype,
...
);
In this syntax, the REFERENCES
keyword is followed by the name of the referenced table, in parentheses. The referenced column is specified in the parentheses after the table name. Note that the referencing column does not have to be the primary key of the referenced table.
Let's say we have two tables, orders
and customers
. The orders
table has a foreign key reference to the customers
table, but the referencing column is not the primary key of the customers
table. Here's how we would create the orders
table:
CREATE TABLE orders (
order_id int PRIMARY KEY,
customer_id int REFERENCES customers (customer_id),
order_date date,
total_amount decimal(10,2)
);
In this example, the customer_id
column in the orders
table is a foreign key that references the customer_id
column in the customers
table. However, customer_id
is not the primary key of the customers
table.
Creating tables with references in SQL is a common task, and it is not always necessary for the referencing column to be the primary key of the referenced table. By using the REFERENCES
keyword in the CREATE TABLE
statement, we can create tables with references to other tables, based on any column or set of columns in the referenced table.