Làm sao để tạo composite primary key trong PostgreSQL?
Làm sao để tạo composite primary key trong PostgreSQL?
Composite (khoá phức hợp) gồm nhiều cột cùng xác định duy nhất một hàng.
-- Khi tạo bảng
CREATE TABLE enrollments (
student_id bigint NOT NULL REFERENCES students(id),
course_id bigint NOT NULL REFERENCES courses(id),
enrolled_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (student_id, course_id)
);
-- Đặt tên
CREATE TABLE t (a int, b int, CONSTRAINT pk_t PRIMARY KEY (a, b));
-- Thêm vào bảng có sẵn
ALTER TABLE enrollments ADD CONSTRAINT pk_enrollments PRIMARY KEY (student_id, course_id);
-- dùng index duy nhất có sẵn (không khoá lâu)
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.