Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何保存分配给哪个国家/地区的组?_Mysql_Sql_Database Design - Fatal编程技术网

Mysql 如何保存分配给哪个国家/地区的组?

Mysql 如何保存分配给哪个国家/地区的组?,mysql,sql,database-design,Mysql,Sql,Database Design,我的数据库中有两个表: countries ( id, name ) groups ( group_id, name, countries ) 如果我在美国、加拿大、德国和荷兰等国家进行分组,并希望将这些国家分组: USA, Canada = North America Germany, Holland = Europe USA, Canada, Germnay, Holland = The World 我如何将其保存在数据库中? 我如何在多个团体中拯救同一个国家? 如果每个国家只有一个组,

我的数据库中有两个表:

countries ( id, name )
groups ( group_id, name, countries )
如果我在美国、加拿大、德国和荷兰等国家进行分组,并希望将这些国家分组:

USA, Canada = North America
Germany, Holland = Europe
USA, Canada, Germnay, Holland = The World
我如何将其保存在数据库中? 我如何在多个团体中拯救同一个国家? 如果每个国家只有一个组,只需在国家中添加组id就很容易了

提前感谢,,
米凯尔这是一种多对多的关系。在关系数据库中,这由关联表表示,该表(至少)有两列-

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'

数据库设计示例:

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';

制作一个类似group_countries的连接表,其中包含group_id和country_id,因此对于同一个国家id和不同的group id,将有多个条目。谢谢!有时候,你不会认为绳子是长的。