在Redshift中,有没有办法为已创建的表添加多个约束?
第一步,创建表(说一个月前)
CREATE TABLE test_user
(
account_id BIGINT DEFAULT NULL encode mostly32,
ingest_timestamp BIGINT DEFAULT NULL ENCODE mostly32,
ingest_date TIMESTAMP DEFAULT NULL ENCODE delta32k,
user_id BIGINT NOT NULL encode mostly32,
group_id BIGINT NOT NULL encode mostly32,
department_id BIGINT NOT NULL encode mostly32,
name VARCHAR(255) DEFAULT NULL ENCODE LZO,
mobile VARCHAR(15) DEFAULT NULL ENCODE LZO,
phone VARCHAR(15) DEFAULT NULL ENCODE LZO,
user_language VARCHAR(15) DEFAULT NULL ENCODE runlength,
deleted INT DEFAULT NULL ENCODE mostly8,
created_at TIMESTAMP DEFAULT NULL ENCODE delta32k,
updated_at TIMESTAMP DEFAULT NULL ENCODE delta32k,
PRIMARY KEY (user_id)
)
sortkey (account_id)
第二步,创建了更多的表,如'test_group','test_department'
第三步,一个月后,我打算像这样在'test_user'表中添加多个约束(但在单独的查询中)
ALTER TABLE test_user ADD CONSTRAINT FK_1 FOREIGN KEY (group_id) REFERENCES test_group (group_id);
ALTER TABLE test_user ADD CONSTRAINT FK_1 FOREIGN KEY (department_id) REFERENCES test_department (department_id);
以上成功。
但是,有没有办法在单个查询中添加多个约束?试过这样的,
选项1 - > ALTER TABLE test_user ADD CONSTRAINT FK_1 FOREIGN KEY (group_id) REFERENCES test_group (group_id),ADD CONSTRAINT FK_1 FOREIGN KEY (department_id) REFERENCES test_department (department_id);
选项2 - > ALTER TABLE test_user ADD CONSTRAINT FK_1 FOREIGN KEY (group_id) REFERENCES test_group (group_id), FK_1 FOREIGN KEY (department_id) REFERENCES test_department (department_id);
但是这两种情况都有这个错误,
An error occurred when executing the SQL command:
ALTER TABLE test_user ADD CONSTRAINT FK_1 FOREIGN KEY (group_id) REFERENCES test_group (group_id), FK_2 FOREIGN KEY (department_id) REFERENCES test_department (department_id); REFERENCES helpdesk_user (user_id)
ERROR: syntax error at or near "FK_2"
有没有办法为已创建的表添加多个约束?请帮忙
在定义它们时,或者即使您完全定义它们也没关系。
Redshift忽略了约束。定义它们没有任何效果,除了优化器可以在创建访问计划时将它们用作附加信息。
但是,我已经在redshift中创建并使用了大量(数十亿行)数据库,并且我没有定义任何类型的单个约束,并且它运行得非常快。
答:不要打扰。
ALTER TABLE
documentation并不表示可以在一个语句中指定多个约束:
ALTER TABLE table_name
{
ADD table_constraint |
DROP CONSTRAINT constraint_name [ RESTRICT | CASCADE ] |
OWNER TO new_owner |
RENAME TO new_name |
RENAME COLUMN column_name TO new_name |
ADD [ COLUMN ] column_name column_type
[ DEFAULT default_expr ]
[ ENCODE encoding ]
[ NOT NULL | NULL ] |
DROP [ COLUMN ] column_name [ RESTRICT | CASCADE ] }
where table_constraint is:
[ CONSTRAINT constraint_name ]
{ UNIQUE ( column_name [, ... ] ) |
PRIMARY KEY ( column_name [, ... ] ) |
FOREIGN KEY (column_name [, ... ] )
REFERENCES reftable [ ( refcolumn ) ]}
另外,Redshift Pitfalls And How To Avoid Them对限制对Redshift查询的影响进行了有趣的检查(参见“谨防约束”部分)。