【发布时间】:2017-09-18 11:44:19
【问题描述】:
我在 MySQL 中创建了两个表。他们的创建查询如下
CREATE TABLE ix_consultant_affected_columns (
master_id int(10) NOT NULL,
logging_session int(10) NOT NULL,
text_id bigint(20) NOT NULL,
table_id int(10) NOT NULL,
column_id int(10) NOT NULL,
PRIMARY KEY (text_id, master_id, logging_session, table_id, column_id)
) ENGINE = INNODB DEFAULT charset = latin1;
CREATE TABLE ix_consultant_query_text (
master_id int(10) NOT NULL,
logging_session int(10) NOT NULL,
text_id bigint(20) NOT NULL,
count int(10) NOT NULL,
discarded tinyint(3) DEFAULT NULL,
query_type varchar(1) DEFAULT NULL,
no_tuner_score float DEFAULT NULL,
num_rows_affected float DEFAULT NULL,
text_plan longtext,
PRIMARY KEY (logging_session, master_id, text_id)
) ENGINE = INNODB DEFAULT charset = latin1;
现在我想在更改查询中应用外键。但它给出了
错误代码:1215。无法添加外键约束
更改查询是:
ALTER TABLE ix_consultant_affected_columns
ADD FOREIGN KEY (master_id) REFERENCES ix_consultant_query_text (master_id),
ADD FOREIGN KEY (logging_session) REFERENCES ix_consultant_query_text (logging_session),
ADD FOREIGN KEY (text_id) REFERENCES ix_consultant_query_text (text_id);
我尝试寻找两者之间的约束或数据类型差异。但我无法确定问题所在。
注意:如果我只使用 logging_session 列运行更改查询,则查询工作正常并应用外键。问题在于 master_id 和 text_id
编辑:
我发现问题是更改查询不在引用表的序列中。 ix_consultant_query_text 表中的主索引序列为:
- logging_session
- master_id
- text_id
因此,当我在引用表的主索引序列中创建更改查询时,它运行良好。
ALTER TABLE ix_consultant_affected_columns
ADD FOREIGN KEY (logging_session,master_id,text_id) REFERENCES ix_consultant_query_text(logging_session,master_id,text_id)
现在的问题是我正在动态创建这个alter查询,那么有没有办法从引用的表中获取列的序列(主索引)?
【问题讨论】:
标签: mysql foreign-keys primary-key alter-table