oracle创建表,设置主外键约束以及插入多条语句
-- 创建部门表
CREATE TABLE departments (
department_id NUMBER(4) CONSTRAINT dept_id_pk PRIMARY KEY,
department_name VARCHAR2(30) CONSTRAINT dept_name_nn NOT NULL,
manager_id NUMBER(6),
location_id NUMBER(4)
);
-- 创建员工表,并设置外键约束指向部门表
CREATE TABLE employees (
employee_id NUMBER(6) CONSTRAINT emp_id_pk PRIMARY KEY,
employee_name VARCHAR2(30) CONSTRAINT emp_name_nn NOT NULL,
department_id NUMBER(4) CONSTRAINT emp_dept_id_fk REFERENCES departments(department_id),
job_id VARCHAR2(10),
salary NUMBER(8,2)
);
-- 插入多条部门数据
INSERT INTO departments (department_id, department_name, manager_id, location_id) VALUES (10, 'IT', 100, 1700);
INSERT INTO departments (department_id, department_name, manager_id, location_id) VALUES (20, 'HR', 200, 1800);
INSERT INTO departments (department_id, department_name, manager_id, location_id) VALUES (30, 'Sales', 300, 1900);
-- 插入多条员工数据,同时使用部门ID作为外键
INSERT INTO employees (employee_id, employee_name, department_id, job_id, salary) VALUES (100, 'John Doe', 10, 'IT_PROG', 80000);
INSERT INTO employees (employee_id, employee_name, department_id, job_id, salary) VALUES (200, 'Jane Smith', 20, 'HR_REP', 70000);
在这个例子中,我们首先创建了部门表departments
,并在其上定义了主键约束。接着我们创建了员工表employees
,并定义了一个外键约束emp_dept_id_fk
,该外键关联到部门表的department_id
字段。然后我们插入了三条部门数据,以及两条员工数据,并使用了部门ID作为外键值。这个例子展示了如何在Oracle数据库中创建表、设置主键和外键约束,以及如何插入多条数据记录。
评论已关闭