Shayal Singh
Shayal Singh

Reputation: 69

How to Select from four tables in sql?

This is the table structure

plinks

ojects

Try

gory

What i want to do is select the ojectname from ojects where the plinks projectidfk is the same in ojects and plinks but select everything from try where the ojectid is equal to the ojectsid where pinks link = 8493284 AND gory id = try goryidfk

Upvotes: 1

Views: 70

Answers (3)

A.J.
A.J.

Reputation: 446

Select obj.objectnamem, try.* from objects as obj 
    inner join plinks on plinks.projectidfk = obj.ojectid
    inner join try on try.projectidfk = obj.ojectid
    inner join gory on gory.goryid = try.goryidfk 
where plinks.link = 8493284

Upvotes: 2

Kamil Gosciminski
Kamil Gosciminski

Reputation: 17147

Using simple JOIN should do this for you. You just connect tables by constraints and then retrieve whatever you want from any of those tables.

Please notice, that if you write a pseudo-code it would look pretty similar to the actual code. You need to use INNER JOINs because you want to be sure, that there are rows that share all those relations and match your criteria on plinks.link.

SELECT o.ojectname, t.*
FROM
  ojects o
  INNER JOIN plinks p ON p.ojectidfk = o.ojectid
  INNER JOIN try t ON t.ojectidfk = o.ojectid
  INNER JOIN gory g ON g.goryid = t.goryidfk
WHERE 
  p.link = 8493284 

Upvotes: 0

SMA
SMA

Reputation: 37023

Try joining all four tables and use where clause for link like:

SELECT o.objectName, t.*
FROM ojects o INNER JOIN plinks p ON o.ojectId = p.ojectidfk
INNER JOIN try t ON o.ojectid = t.ojectidfk
INNER JOIN gory g ON g.goryid = t.goryidfk
WHERE p.link = 8493284

Upvotes: 0

Related Questions