gpt4 book ai didi

mysql - 数据库关系中单值数据到多值数据

转载 作者:行者123 更新时间:2023-11-29 08:46:40 25 4
gpt4 key购买 nike

我很难想象这一点。我只是没有脑子去做。

我有一个名为 reports 的表.

---------------------------------------------
| 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_of_badsset_it_belongs_tobads table 。这样如果我想获取整组数据即set1调用reports表我能做到。

示例:嘿,报告表.. 调出包含 report_id 的行123 。好的,谢谢。现在获取 bads 中的所有行有 set_of_bads来自具有 report_id 的行的值123 ,在 set_it_belongs_to field 。谢谢。

最佳答案

试试这个,

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

并确保reports表的主键set_of_bads

关于mysql - 数据库关系中单值数据到多值数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12391712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com