Furkan Gözükara
Furkan Gözükara

Reputation: 23860

How to select 2 variables from another table SQL server query

Alright here the question

Table 1:

Id1, Id2

Table 2

Id, Username

Now this Table 1 Id1 and Id2 variables are unique keys in Table 2

I want to select Table 1 all values as this

Username1, Username2

So how can I write this query ?

Full example

Table 1

1,3
3,5

Table 2

1,Furkan
3,Obama
5,USA

Result

Furkan, Obama
Obama, USA

Thank you

Upvotes: 1

Views: 2962

Answers (3)

sangram parmar
sangram parmar

Reputation: 8736

Try this

here is http://www.sqlfiddle.com/#!2/e10b7/2/0

CREATE TABLE table1
(
     Id1 int  primary key, 
     Id2 int
);

INSERT INTO table1
VALUES (1, 3),
       (3, 5);

CREATE TABLE table2
(
     Id int  primary key, 
     Username varchar(255)
);

INSERT INTO table2
VALUES (1, 'Furkan'),
       (3, 'Obama'),
       (5, 'USA');

Your SQL query

select 
    (select Username 
     from table2 as t2 
     where t2.Id = t1.Id1) as coloum1 ,
    (select Username 
     from table2 as t2 
     where t2.Id = t1.Id2) as coloum2 
from table1 as t1

Upvotes: 3

Old Pro
Old Pro

Reputation: 25557

See SQL Fiddle for live example

SELECT a.Username AS name_1, b.Username AS name_2 FROM
  t1 JOIN t2 AS a ON t1.Id1 = a.Id
     JOIN t2 AS b ON t1.Id2 = b.Id

Upvotes: 1

Mixthos
Mixthos

Reputation: 1087

SELECT table2_1.Username AS Username1, table2_2.Username AS Username2
FROM table1
JOIN table2 AS table2_1 ON table1.Id1 = table2_1.Id
JOIN table2 AS table2_2 ON table1.Id2 = table2_2.Id

Upvotes: 1

Related Questions