0

I have two tables - player, which stores players data, and similar table team. I want to select from these two tables name and surname of player and name of team to which one he belongs. I used this query:

SELECT player.name, player.surname,
   team.name AS teamname 
FROM player, team 
WHERE player.id_player=team.id_team 

But as result i only have only one player from each team, and of course i want a full list of players with names of team.

Anyone has an idea?

2
  • 1
    Can you provide the schema for these two tables? Commented Jan 9, 2016 at 18:21
  • Player has id_player, name, surname, and team_id_team. Team has id_team and name Commented Jan 9, 2016 at 18:24

3 Answers 3

3

I think you need to join on the team id. I am guessing something similar to this will work:

SELECT p.name, p.surname, t.name AS teamname 
FROM player p JOIN
     team t
     ON p.team_id_team = t.id_team ;
----------^ Note the change here

Also:

  • Learn proper JOIN syntax. Simple rule: Never use commas in the FROM clause. Always use explicit JOIN syntax.
  • Table aliases make a query easier to write and to read.
  • If you have players without a valid team, then use a LEFT JOIN instead of JOIN.
Sign up to request clarification or add additional context in comments.

2 Comments

Good catch on the error in the join condition. Based on the schema provided in the comment, it certainly seems you have the correct answer.
With this query i have a valid teams, left join dont work, whats the difference?
2

You must use JOIN to "connect" the tables. With "WHERE" you only can exclude rows;

SELECT
  p.name,
  p.surname,
  t.name AS teamname 
FROM player p
LEFT JOIN team t ON p.id_player = t.id_team ;

5 Comments

this query shows wrong names of teams, and when it runs out of teamnames shows null, Grodon Linoff's answer works well
@Janusz Bieraszewski this is because there is typo in your query and author of this answer just copy it
@Evgeny - Yes i have seen the difference in the field names, but i canz see othe relations
This is because the join condition is incorrect. I understand the answer, but not the upvotes.
@Janusz Bieraszewski - if you post your Table schema i can correct my answer
1

You should use left join:

SELECT p.name, p.surname,
   t.name AS teamname 
FROM player p
left join team t on t.id_team=p.id_team 

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.