我的Android应用程序中有三个表。
Table Animal Table Group TableGroup_Animal
idAnimal idGroup idAnimal
AnimalName groupName idGroup
我想知道如何进行查询以获取组内的所有动物。我提出的查询是
select
Groups.groupName
from
Groups,
Animal,
tableGrupo_Animal
where
Animal.idanimal = tableGroup_Animal.fkanimal
and
Groups.idgrupo = tableGrupo_Animal.fkgrupo
group by
group.groupName
此外(仅显示第一行)
select
*
from
Animal
INNER JOIN " + tableGroup + " ON Animal.idanimal = Group.idGroup
where
Group.groupName = ' " + groupName +
正如我所说,我希望将所有动物都集中在一个群体中,我该怎么做?感谢
答案 0 :(得分:1)
我在sqlite中重新创建了数据库并对其进行了测试。这个SQL工作得很好。我建议你重命名你的桌子" Group"因为它是SQL中的保留字,你必须每次都像我在这个sql中那样回复它。
select a.AnimalName, g.groupName
from Animal a
JOIN TableGroup_Animal tga ON a.idAnimal = tga.idAnimal
JOIN `Group` g on g.idGroup= tga.idGroup;
这是我创建的架构和数据,以帮助任何人尝试原型。
CREATE TABLE `Animal` (
`idAnimal` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
`animalName` varchar(128)
);
CREATE TABLE `Group` (
`idGroup` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
`groupName` varchar(128)
);
CREATE TABLE `TableGroup_Animal` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
`idAnimal` integer,
`idGroup` integer
);
--Seeding animal
insert into `Animal` (animalName) values ('cat');
insert into `Animal` (animalName) values ('Rat');
insert into `Animal` (animalName) values ('Zebra');
insert into `Animal` (animalName) values ('Platypus');
--seeding group
insert into `Group` (groupName) values ('small');
insert into `Group` (groupName) values ('medium');
insert into `Group` (groupName) values ('large');
---seeding group animal pivot table
insert into TableGroup_Animal (idAnimal, idGroup) values (3,2);
insert into TableGroup_Animal (idAnimal, idGroup) values (3,3);
insert into TableGroup_Animal (idAnimal, idGroup) values (1,2);
insert into TableGroup_Animal (idAnimal, idGroup) values (4,2);
insert into TableGroup_Animal (idAnimal, idGroup) values (2,1);
);
insert into TableGroup_Animal (idAnimal, idGroup) values (2,1);
答案 1 :(得分:1)
执行此查询:
select * from Animal INNER JOIN tableGrupo_Animal ON Animal.idanimal = tableGrupo_Animal.fkanimal INNER JOIN Grupos ON Grupos.idgrupo = tableGrupo_Animal.fkgrupo where Grupos.nomegrupo='wwrt'