Having these tables into a db:
Athlete with fields: athlete_id, name, surname, date_of_birth, height, weight, bio, photo_id
AthletePhoto with fields: photo_id, photo, mime_type
AthleteResult with fields: athlete_id, gold, silver, bronze
Game with fields: game_id, city, year
The db 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
.
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:
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
Advertisement
Answer
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. 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.
JOIN Combines different tables row-wise
UNION Combines different tables column-wise