我的数据库中有两张表:
countries ( id, name )
groups ( group_id, name, countries )
如果我在各个国家/地区获得了美国,加拿大,德国和荷兰,并希望将其分组:
USA, Canada = North America
Germany, Holland = Europe
USA, Canada, Germnay, Holland = The World
如何在我的数据库中保存? 如何将同一个国家/地区保存在一个以上的组中? 如果每个国家只有一个组,只需在国家/地区添加group_id就可以轻松实现。
提前致谢, 的Mikael
答案 0 :(得分:0)
这是一对多关系。在关系数据库中,这由关联表表示,该表具有(至少)两列 -
country_groups ( country_id, group_id )
然后,当涉及到查询时,您将包含联接以引入此表,例如,对于北美的所有国家/地区:
SELECT c.name FROM countries c
INNER JOIN country_groups cg ON cg.country_id = c.id
INNER JOIN groups g ON cg.group_id = g.group_id
WHERE g.name = 'North America'
答案 1 :(得分:0)
示例数据库设计:
CREATE TABLE Countries
(`id` INT auto_increment primary key , `name` varchar(30))
;
INSERT INTO Countries
(`name`)
VALUES
('Germany'),('USA'),('Holland'),('Canada')
;
CREATE TABLE Groups_Countries
(`id` INT auto_increment primary key , Countries_ID int, Groups_id int)
;
INSERT INTO Groups_Countries
(Countries_id,Groups_id)
VALUES
(2,1),(4,1),(1,2),(3,2),(1,3),(2,3),(3,3),(4,3)
;
CREATE TABLE Groups
(`id` INT auto_increment primary key , `name` varchar(30))
;
INSERT INTO Groups
(`name`)
VALUES
('North America'),('Europe'),('The World')
;
SQL查询
SELECT c.name FROM Countries c
JOIN Groups_Countries gc
ON c.ID = gc.countries_ID
JOIN Groups g
ON g.id = gc.Groups_ID
WHERE g.name = 'North America';
SELECT c.name FROM Countries c
JOIN Groups_Countries gc
ON c.ID = gc.countries_ID
JOIN Groups g
ON g.id = gc.Groups_ID
WHERE g.name = 'Europe';
SELECT c.name FROM Countries c
JOIN Groups_Countries gc
ON c.ID = gc.countries_ID
JOIN Groups g
ON g.id = gc.Groups_ID
WHERE g.name = 'The World';