0

I want to select the total number of appearance of a single player in two other tables.

Here is my database structure (postgres):

Table: Player
id              integer

Table: World Champions
id              integer
year            date
player_id       integer

Table: European Champions
id              integer
year            date
player_id       integer

The id on table player is also available in table "World Champions" and "European Champions" (player_id). I want to select the data as following:

player.id       worldChampionTitles     europeanChampionTitles
1               3                       4
2               1                       0
3               0                       0
4               1                       1

But I have no Idea how to write my select query for that.

1
  • Left join your tables on player_id and use player.id as grouping field. Commented Feb 10, 2016 at 8:35

1 Answer 1

1

Easy with subqueries:

SELECT p.id
     , (SELECT count(*) FROM "World Champions" AS c WHERE c.player_id = p.id)
         + (SELECT count(*) FROM "European Champions" AS c WHERE c.player_id = p.id)
FROM Player AS p
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.