user1565893
user1565893

Reputation: 43

how to get combine from Two select statements

my table is,

ID   First_Name    Last_name    manager_ID     Unique_ID
12    Jon           Doe          25             CN=Jon Doe, DC=test,DC=COM
25    Steve         Smith        39             CN=steve smith, DC=test,dc=com

I want to write a sql that will give me manager's unique ID,

select manager_id from test where ID = '12'

this will give me users manager_ID

select unique_id from test where ID = '25' 

can i combine above sql in one statement that will give me user's manager's unique_id as output?

Upvotes: 1

Views: 52

Answers (2)

Nikhil
Nikhil

Reputation: 3950

Instead of joining it to the same table, you can also make a nested subquery statement like this.

SELECT unique_id FROM test WHERE ID =(SELECT manager_id FROM test WHERE ID = 12);

The inner query outputs the manager_id where id of person equals 12 and the outer query gives the unique_id of the related manager.

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1269503

You are looking for a self-join:

select m.unique_id
from test t join
     test m
     on t.manager_id = m.id
where t.ID = 12;

Note that I remove the single quotes around 12. Presumably, id is an integer. You should not be comparing an integer to a string.

Upvotes: 2

Related Questions