Mateusz
Mateusz

Reputation: 331

Using select inner join in sql

So I have 5 tables:

dane_osobowe:
(PK) id
imie

druzyna:
(PK) id
nazwa

gracz:
(PK) id
(FK) dane_osobowe
(FK) pozycja

kontrakt:
(PK) id
(FK) gracz
(FK) druzyna

pozycja:
(PK) id
nazwa

How can I chose all "gracz" from druzyna "1" which has "pozycja" 2? I tried something like this:

SELECT * 
   FROM gracz AS gr 
INNER JOIN kontrakt AS kg
   ON gr.ID = kg.Gracz
INNER JOIN Druzyna AS d
   ON kg.Druzyna = d.ID
      WHERE d.ID = 1
INNER JOIN pozycja as poz
   ON poz.id = gracz.pozycja
      WHERE gracz.pozycja = 2

But it doesn't work :/ Somebody have idea what I'm doing wrong?

Upvotes: 0

Views: 44

Answers (1)

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

Try this:

SELECT * 
   FROM gracz AS gr 
INNER JOIN kontrakt AS kg
   ON gr.ID = kg.Gracz
INNER JOIN Druzyna AS d
   ON kg.Druzyna = d.ID
--Remove the where condition from here       
INNER JOIN pozycja as poz
   ON poz.id = gracz.pozycja
      WHERE gracz.pozycja = 2
and d.ID = 1   --Add it over here using "and"

ie, move all the where conditions together at the last.

EDIT:

To get the selected columns you can specify it like this:

SELECT d.id, gr.dane_osobowe, poz.nazwa
   FROM gracz AS gr 
INNER JOIN kontrakt AS kg
   ON gr.ID = kg.Gracz
INNER JOIN Druzyna AS d
   ON kg.Druzyna = d.ID
--Remove the where condition from here       
INNER JOIN pozycja as poz
   ON poz.id = gracz.pozycja
      WHERE gracz.pozycja = 2
and d.ID = 1   --Add it over here using "and"

Upvotes: 2

Related Questions