Quartermain
Quartermain

Reputation: 173

Use the foreign key that a query selects to get data within the same query

I have this issue with a query I am trying to build. The idea is that I have 3 tables where two have foreign keys. I want to make a query that selects the foreign key from TABLE A and uses the same key to get data from key B.

So it will look like this:

SELECT 
    id, foreignKey1 
FROM 
    tableA 
    (SELECT id FROM tableB WHERE ID = foreignKey1);

But somehow I am not able to do this or find any good documentation about it.

Upvotes: 0

Views: 33

Answers (2)

Mahesh
Mahesh

Reputation: 13

If you want to make a query that selects the foreign key from TABLE A and uses the same key to get data from key B, below should work,

SELECT id, foreignKey1 
FROM tableB 
WHERE id IN (SELECT id FROM tableA);

but joins always gives better performance than sub queries, you can use below query,

SELECT b.id, b.foreignKey1 
FROM tableB b 
INNER JOIN tableA ON a.id = b.id;

Upvotes: 0

Siyual
Siyual

Reputation: 16917

This is a simple INNER JOIN:

Select      *
From        TableA  A
Inner Join  TableB  B   On  A.ForeignKey1 = B.Id

Upvotes: 1

Related Questions