Mysql 数据库关系中的单值数据到多值数据
我很难想象这一切。我只是没有头脑去做 我有一个名为报告的表Mysql 数据库关系中的单值数据到多值数据,mysql,sql,database,database-design,relational-database,Mysql,Sql,Database,Database Design,Relational Database,我很难想象这一切。我只是没有头脑去做 我有一个名为报告的表 --------------------------------------------- | report_id | set_of_bads | field1 | field2 | --------------------------------------------- | 123 | set1 | qwe | qwe | --------------------------------
---------------------------------------------
| report_id | set_of_bads | field1 | field2 |
---------------------------------------------
| 123 | set1 | qwe | qwe |
---------------------------------------------
| 321 | 123112 | ewq | ewq |
---------------------------------------------
我有另一个表名为bads
。此表包含错误数据的列表
-------------------------------------
| bad_id | set_it_belongs_to | field2 | field3 |
-------------------------------------
| 1 | set1 | qwe | qwe |
-------------------------------------
| 2 | set1 | qee | tte |
-------------------------------------
| 3 | set1 | q44w | 3qwe |
-------------------------------------
| 4 | 234 | qoow | 3qwe |
-------------------------------------
我想设置主键到外键的关系。我的问题是,如何将字段set\u of_bads
连接到bads
表中的set\u它所属的
。这样,如果我想通过调用reports
表来获取set1
的整个数据集,我就可以这样做
示例:hey reports表。。调出具有报告id的行
123
。好的,谢谢。。现在,在设置它所属的字段中,从报告id为的行中,获取bads
中具有设置bads
值的所有行。谢谢。试试这个
SELECT a.*, -- will display all records from reports table
b.* -- will display all records from bads table
FROM reports a
INNER JOIN bads b
ON a.set_of_bads = b.set_it_belongs_to
WHERE a.report_ID = 123
更新1
在CREATE TABLE
语句中,在bads
表上指定外键约束
CREATE TABLE bads
(
bad_id INT AUTO_INCREMENT ,
set_it_belongs_to VARCHAR(50),
field2 VARCHAR(50),
field3 VARCHAR(50),
CONSTRAINT bads_pk PRIMARY KEY (bad_id),
CONSTRAINT bads_fk FOREIGN KEY (set_it_belongs_to)
REFERENCES reports(set_of_bads)
);
并确保报告
表的主键
为set\u of_bads
谢谢John的建议,也谢谢您在我的帖子中修复了该表的格式。它使它看起来更好。实际上,我刚刚编辑了我的文章,所以还有更多内容。实际上我只是想设置一个外键关系。@SofianeMerah那么您需要指定一个约束。看看我最新的答案:谢谢。现在,set\u of_bad
是否需要成为reports
表中的主键?因为我想将主键保留为reports\u id
。信息上是的。如果您为report_id指定了唯一约束,则仍然可以在report_id上具有唯一键。根据定义,外键是另一个表中的主键。