[英]Get all tables data with Node.js and SQLite
Having these tables into a db:将这些表放入数据库:
Athlete with fields: athlete_id, name, surname, date_of_birth, height, weight, bio, photo_id
具有以下字段的运动员:运动员athlete_id, name, surname, date_of_birth, height, weight, bio, photo_id
AthletePhoto with fields: photo_id, photo, mime_type
具有以下字段的AthletePhoto : photo_id, photo, mime_type
AthleteResult with fields: athlete_id, gold, silver, bronze
带有字段的AthleteResult : athlete_id, gold, silver, bronze
Game with fields: game_id, city, year
带字段的游戏: game_id, city, year
The db model:数据库 model:
The code so far can only send data for one of the tables:到目前为止的代码只能为其中一个表发送数据:
db.serialize(function () {
db.all(
'SELECT athlete_id, name, surname FROM Athlete',
function (err, rows) {
return res.send(rows);
}
);
});
so it uses that query: SELECT athlete_id, name, surname FROM Athlete
.因此它使用该查询: SELECT athlete_id, name, surname FROM Athlete
。
Is there a way to combine the tables and send all data?有没有办法合并表格并发送所有数据?
I've tried to combine 2 tables, Athlete and AthletePhoto but didn't send any data:我尝试合并 2 个表,Athlete 和 AthletePhoto,但没有发送任何数据:
SELECT athlete_id, name FROM Athlete UNION SELECT game_id, city, year FROM Game UNION SELECT photo_id as athlete_id, mime_type as name FROM AthletePhoto
Assuming that your database structure correctly represents your application needs, the query which you are trying to make will look something like this:假设您的数据库结构正确地代表了您的应用程序需求,您尝试进行的查询将如下所示:
SELECT
a.athlete_id, a.name, a.surname, a.date_of_birth, a.bio, a.height, a.weight,
ap.photo, ap.mime_type,
ar.gold, ar.silver, ar.bronze,
g.city, g.year
FROM
(
(
(Athlete a JOIN AthletePhoto ap ON a.photo_id = ap.photo_id)
JOIN
AthleteResults ar ON a.athlete_id = ar.athlete_id
)
JOIN
Game g ON ar.game_id = g.game_id
)
There is one mistake in Athlete table, that date_of_birth column is defined twice. Athlete 表中有一个错误,date_of_birth 列定义了两次。 You should rename anyone of them.您应该重命名其中的任何一个。 There is no need to use UNION in your query if you want to combine results of different tables, use JOIN instead.如果要组合不同表的结果,则无需在查询中使用 UNION,而是使用 JOIN。
JOIN Combines different tables row-wise JOIN按行组合不同的表
UNION Combines different tables column-wise UNION按列组合不同的表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.