How can I refer to one table several times in one query?

Sometimes I need to process the same table as two separate tables. What is the solution?

+5
source share
4 answers

Use an alias, such as a variable name in your SQL:

select
    A.Id,
    A.Name,
    B.Id as SpouseId,
    B.Name as SpouseName
from
    People A
    join People B on A.Spouse = B.id
+6
source

You can reference, just use a table alias

select a.EmployeeName,b.EmployeeName as Manager
from Employees A
join Employees B on a.Mgr_id=B.Id
+9
source

:

SELECT t1.col1, t2.col3
FROM tbl t1
INNER JOIN tbl t2
    ON t1.col1 = t2.col2
+2

-

SELECT * FROM x1 AS x,y1 AS y

, ,

;WITH ctx AS 
( select * from z)
SELECT y.* FROM ctx AS c1,ctx AS c2

- , - :

SELECT * 
INTO #monkey
FROM chimpanzee

SELECT * FROM #monkey m1,#monkey m2

DROP TABLE #MONKEY

. ( ), - .

+2

All Articles