问题
I have two tables:
CREATE TABLE first_table(
my_id TEXT(6) NOT NULL,
content VARCHAR(30) NOT NULL,
PRIMARY KEY(my_id(6))
) Engine=InnoDB charset utf8mb4 collate utf8mb4_general_ci;
CREATE TABLE second_table(
another_id TEXT(6) NOT NULL,
my_id TEXT(6) NOT NULL,
another_content VARCHAR(30) NOT NULL,
PRIMARY KEY(another_id(6))
) Engine=InnoDB charset utf8mb4 collate utf8mb4_general_ci;
But in the second table I can't create a foreign key that references the first table, first I've tried this:
ALTER TABLE second_table
ADD FOREIGN KEY (my_id)
REFERENCES first_table(my_id)
ON DELETE CASCADE ON UPDATE CASCADE;
And got this error:
ERROR 1170 (42000): BLOB/TEXT column 'my_id' used in key specification without a key length
MariaDB [base_ventas]>
So, I tried to specify the key length like this:
ALTER TABLE second_table
ADD FOREIGN KEY (my_id(6))
REFERENCES first_table(my_id)
ON DELETE CASCADE ON UPDATE CASCADE;
And I got this error:
ERROR 1005 (HY000): Can't create table `base_ventas`.`#sql-1a08_23c`
(errno: 150 "Foreign key constraint is incorrectly formed")
This doesn't happen with numeric ids but I need to have string type ids, it can be done, or I am missing something?
回答1:
I am sorry to inform that it's not possible.
According to MySql Documentation:
Index prefixes on foreign key columns are not supported. One consequence of this is that BLOB and TEXT columns cannot be included in a foreign key because indexes on those columns must always include a prefix length.
And MariaDB Documentation:
The columns in the child table must be an index, or the leftmost part of an index. Index prefixes are not supported (thus, TEXT and BLOB columns cannot be used as foreign keys)
If you really need alphanumeric keys, consider using something like char or varchar instead. The easiest, most generic, and most common approach is to use numeric keys, such as INT.
来源:https://stackoverflow.com/questions/46201367/how-can-i-create-a-foreign-keys-of-text-type-in-mariadb-or-mysql