最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

MySQL Adding Foreign Key Constraint to Table Using a JSON Expression - Stack Overflow

programmeradmin4浏览0评论

I am trying to add an index and a foreign key constraint to an existing table, each of which references a JSON expression.

The ADD INDEX command below is working by itself, but the statement fails when I add the ADD CONSTRAINT.

I'd appreciate any advice regarding what I'm doing wrong. Thanks.

ALTER TABLE MyTable 
ADD INDEX 'MyTable_5' ( ( JSON_VALUE( MyTable, '$.someData' ) )  ),
ADD CONSTRAINT 'MyTable_5FK' FOREIGN KEY ( JSON_VALUE( MyTable, '$.someData' ) )  REFERENCES OtherTable (PK);

I am trying to add an index and a foreign key constraint to an existing table, each of which references a JSON expression.

The ADD INDEX command below is working by itself, but the statement fails when I add the ADD CONSTRAINT.

I'd appreciate any advice regarding what I'm doing wrong. Thanks.

ALTER TABLE MyTable 
ADD INDEX 'MyTable_5' ( ( JSON_VALUE( MyTable, '$.someData' ) )  ),
ADD CONSTRAINT 'MyTable_5FK' FOREIGN KEY ( JSON_VALUE( MyTable, '$.someData' ) )  REFERENCES OtherTable (PK);
Share Improve this question asked Mar 10 at 20:02 ChrisChris 1417 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 1

The syntax for ADD INDEX is:

ADD {INDEX | KEY} [index_name]
[index_type] (key_part,...) [index_option] ...

Notice that the syntax inside the parentheses is key_part, and key_part can be either a column name or an expression.

But the syntax for a foreign key is (see documentation):

ADD [CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (col_name,...)
reference_definition

Notice that it only allows column names, not expressions. So you can't use a JSON_VALUE() call as a foreign key.

I think you may be able to create a stored generated column using the expression, and then make that a foreign key. However, this isn't allowed to use some of the ON UPDATE and ON DELETE options.

ALTER TABLE MyTable
ADD COLUMN someData INT GENERATED ALWAYS AS (JSON_VALUE(MyTable, '$.someData')) STORED,
ADD CONSTRAINT MyTable_5FK FOREIGN KEY (someData) REFERENCES OtherTable (PK);
发布评论

评论列表(0)

  1. 暂无评论