从具有外键的亲戚中选择?

时间:2014-11-02 02:37:00

标签: mysql select foreign-keys

我有这些表格:

create table CLIENTE (
idCliente int primary key auto_increment,
name varchar(255)


create table ANIMAL (
idAnimal int primary key,
name varchar(255),
foreign key (idCliente) references CLIENTE (idClinete) on delete set null on update cascade

如何从客户John列出(使用Select * from methood)动物的名字? 它是一种可执行文件,所以我知道如果我运行代码它实际上不会显示名称,但除此之外我怎么才能生成代码?

1 个答案:

答案 0 :(得分:2)

您需要在idCliente表中添加ANIMAL列:

create table ANIMAL (
    idAnimal INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255),
    idCliente INT,
    FOREIGN KEY (idCliente) REFERENCES CLIENTE (idCliente) ON DELETE SET NULL ON UPDATE CASCADE
);

然后在JOIN

中使用它
SELECT a.*
FROM ANIMAL AS a
JOIN CLIENTE AS c ON a.idCliente = c.idCliente
WHERE c.name = 'John';