CREATE TABLE abc
(
id INT NOT NULL,
class VARCHAR(10) NOT NULL,
division VARCHAR(1) NOT NULL,
dateOfxyz DATE NOT NULL,
PRIMARY KEY (id, class, division, dateOfxyz)
)
现在,我想在另一个表中访问此主键的id类和分区部分作为外键,我可以这样做吗?如果是,那怎么样?
答案 0 :(得分:0)
我不明白你的问题 在引用表中,必须有一个索引,其中外键列以相同的顺序列为第一列。 https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
MariaDB [sandbox]> drop table if exists t;
Query OK, 0 rows affected (0.03 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> CREATE TABLE abc
-> (
-> id INT NOT NULL,
-> class VARCHAR(10) NOT NULL,
-> division VARCHAR(1) NOT NULL,
-> dateOfxyz DATE NOT NULL,
-> PRIMARY KEY (id, class, division, dateOfxyz)
-> );
ERROR 1050 (42S01): Table 'abc' already exists
MariaDB [sandbox]>
MariaDB [sandbox]> drop table if exists t;
Query OK, 0 rows affected, 1 warning (0.00 sec)
MariaDB [sandbox]> create table t
-> (id INT NOT NULL,
-> class VARCHAR(10) NOT NULL,
-> division VARCHAR(1) NOT NULL);
Query OK, 0 rows affected (0.03 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> alter table t
-> add foreign key tfk1(id,class,division) references abc(id,class,division);
Query OK, 0 rows affected (0.12 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [sandbox]>
MariaDB [sandbox]> show create table t;
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| t | CREATE TABLE `t` (
`id` int(11) NOT NULL,
`class` varchar(10) NOT NULL,
`division` varchar(1) NOT NULL,
KEY `tfk1` (`id`,`class`,`division`),
CONSTRAINT `tfk1` FOREIGN KEY (`id`, `class`, `division`) REFERENCES `abc` (`id`, `class`, `division`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |