错误代码:1822。无法添加外键约束。引用表“ pwlhseis”中约束“ ekdromes_ibfk_1”的缺少索引

时间:2019-01-11 21:13:29

标签: mysql sql mysql-workbench

我有这两个表:

<html><body><H3>Contact Info</H3>
<table border=1>
<tr>
<th> Solution Name </th>
 <th> Start Time </th> 
 <th> Run Start </th>
</tr>
 <tr>
 <td>Test maxrun Solution</td>
 <td>2019-01-11T11:58:48.077</td>
 <td>00:00:00</td>
 </tr>
 <tr>
 <td>Test maxrun Solution1</td>
 <td>2019-01-09T10:12:21.643</td>
 <td>01:46:26</td>
 </tr>
 <tr>
 <td>Test maxrun Solution2</td>
 <td>2018-12-28T14:50:16.270</td>
 <td>21:08:32</td>
 </tr>
 </table>
 </body>
 </html>

并且:

create table pwlhseis(
ma int,
hmeromhnia date,
wra time,
hmer_diek date,
ae_po int,
amka_po int,
constraint foreign key (amka_po) references pelates(amka),
primary key (ma));

然后:

create table ekdromes(
ae int,
diarkeia int,
proorismos varchar(20),
kostos float,
timh float,
afeteria varchar(20),
hm_enarkshs date,
primary key (ae));

第一个更改效果很好,当我尝试运行第二个更改时,出现1822错误。有什么问题吗?

2 个答案:

答案 0 :(得分:2)

您已将主键定义为pwlhseis(ma)。那就是您应该用于外键引用的地方。

就我个人而言,我将主键和外键命名为匹配项,因此,这看起来像:

create table pwlhseis (
    pwlhseis_id int primary key,
    . . .
);

create table ekdromes (
    ekdromes_id int primary key,
    . . .
    pwlhseis_id int,
);

alter table ekdromes 
  add constraint fk_ekdromes_pwlhseis foreign key (pwlhseis_id) references pwlhseis(pwlhseis_id);

答案 1 :(得分:1)

如果您想针对pwlhseis.ae_po使用外键,则此列需要具有唯一约束。

这意味着:

  • 它是表的主键(不是),或者
  • 它还有一个额外的独特约束。

如果要尝试第二个选项,可以运行:

alter table pwlhseis add constraint uq1 unique (ae_po);

然后,您可以尝试再次添加外键。