我有三个不同的表:person,person_pet和pet
create table person (
id integer primary key,
name text
);
create table person_pet (
person_id integer,
pet_id integer primary key
);
create table pet (
id integer primary key,
breed text,
owner integer
);
之后,我插入了一些值:
insert into person (id, name)
values (0, "Name1"), (1, "Name2"), (2, "Name3");
insert into person_pet (person_id, pet_id)
values (0,1), (1,0), (2,3), (1,2);
insert into pet (id, breed, owner)
values (0, "PetA", null), (1, "PetB", null), (2, "PetC", null), (3, "PetD", null);
我想将table pet中owner列的数据更新为person_pet表中显示的所有者的实际id。也就是说,我想要以下结果:
PET表
id breed owner
0 PetA 1
1 PetB 0
2 PetC 1
3 PetD 2
我使用select子查询尝试了这个SQL查询:
update pet set owner = (
select person.id
from person, person_pet, pet
where person.id = person_pet.person_id and
person_pet.pet_id = pet.id
);
这产生了这个输出(填写只有一个所有者的id):
PET表
id breed owner
0 PetA 1
1 PetB 1
2 PetC 1
3 PetD 1
如果我自己运行子查询,
select person.id
from person, person_pet, pet
where person.id = person_pet.person_id and
person_pet.pet_id = pet.id;
我想要的结果出现了:
PET表
id breed owner
0 PetA 1
1 PetB 0
2 PetC 1
3 PetD 2
但是在使用更新命令时我没有设法得到这个。
答案 0 :(得分:0)
我做了这个练习作为SQL SERVER解决方案, 可能对你有帮助:
update pet set owner = person.id
from pet inner join person_pet on pet.id = person_pet.pet_id
inner join person on person.id = person_pet.person_id
使用此输出:
id breed owner
0 PetA 1
1 PetB 0
2 PetC 1
3 PetD 2
答案 1 :(得分:0)
对于SQLite,请尝试以下格式:
UPDATE pet
SET owner = (
SELECT PER.id
FROM person PER
INNER JOIN person_pet PPE ON PPE.person_id = PER.id
INNER JOIN pet PET ON PET.id = PPE.pet_id)
WHERE id IN (SELECT id FROM pet);