gpt4 book ai didi

database - SQLite - 连接 3 个数据库表

转载 作者:搜寻专家 更新时间:2023-10-30 19:47:25 24 4
gpt4 key购买 nike

我的数据库中有这 3 个表:

用户: 键:ID(主键)|姓名

专辑: 键:ID(主键)|姓名 | USER_ID

图片: 带键:ID(主键)|姓名 |专辑 ID

在Albums表中,USER_ID是拥有相册的用户ID,在Pictures表中,ALBUM_ID是相册的ID图片属于。

我正在尝试打印拥有它的用户旁边的每张照片,我希望我的结果是这样的:

Pictures.name    |    Users.name

因此,我尝试使用 Album_ID 将图片连接到相册,然后将相册表连接到用户,但没有成功。

最佳答案

您连接的不是表,而是连接数据库,这样您就可以访问数据库中的表。

因此,一旦您连接到数据库,要获取您的列表,您将使用/运行查询:-

SELECT Pictures.name, Users.name 
FROM Pictures
JOIN Albums ON Pictures.ALBUM_ID = Albums.ID
JOIN Users ON Albums.ALBUM_ID = Users.USER_ID
;

例子

表格

例如,连接的数据库有下表(注意表名和列名为方便起见而更改):-

enter image description here enter image description here enter image description here

结果

使用与上述类似的查询(只是表名和列名不同):-

SELECT _pictures.name, _users.name 
FROM _pictures
JOIN _albums ON _pictures.albumid = _albums.id
JOIN _users ON _albums.userid = _users.id
;

结果:-

enter image description here


该示例基于以下 SQL 来创建和填充表:-

CREATE TABLE IF NOT EXISTS _users (ID INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE IF NOT EXISTS _albums (ID INTEGER PRIMARY KEY, name TEXT, userid INTEGER);
CREATE TABLE IF NOT EXISTS _pictures (ID INTEGER PRIMARY KEY, name TEXT, albumid INTEGER);
INSERT INTO _users VALUES
(1,'Fred'),
(2,'Bert'),
(3,'Harry')
;
INSERT INTO _albums VALUES(1,'Ablum owned by Fred',1),
(2,'Another Album owned by Fred',1),
(3,'Another Album owned by Bert',2),
(4,'Another Album owned by Harry',3),
(5,'An Album for Fred',1),
(6,'The Album of Harry',3),
(7,'Harry the Album',3),
(8,'A taste of Bert',2)
;
INSERT INTO _pictures VALUES
(1,'Picture for Album 1',1),
(2,'Picture for Album 2',2),
(3,'Picture for Album 3',3),
(4,'Picture for Album 1',4),
(5,'Picture for Album 1',5),
(6,'Picture for Album 1',6),
(7,'Picture for Album 1',7),
(8,'Picture for Album 1',8)
;

关于database - SQLite - 连接 3 个数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640501/

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