views:

90

answers:

4

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

+2  A: 

Use an alias:

SELECT t1.col1, t2.col3
FROM tbl t1
INNER JOIN tbl t2
    ON t1.col1 = t2.col2
thecoop
+8  A: 

You can reference, just be sure to use a table alias

select a.EmployeeName,b.EmployeeName as Manager
from Employees A
join Employees B on a.Mgr_id=B.Id
Sparky
+3  A: 

Use an alias like 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
Aaron
+2  A: 

Alias is the most obvious solution

SELECT * FROM x1 AS x,y1 AS y

However if the table is the result of a query a common table expressions is quite usefull

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

A third solution -- suitable when your query lasts a long time -- is temporary tables:

SELECT * 
INTO #monkey
FROM chimpanzee

SELECT * FROM #monkey m1,#monkey m2

DROP TABLE #MONKEY

Note a common table expression is only available for one query (the query directly after it), and temporary tables last for the whole batch.

Hassan Syed
in your first example, you use the old join syntax: `SELECT * FROM x1 AS x,y1 AS y` it is much better to use the current join syntax: `SELECT * FROM x1 AS x INNER JOIN y1 AS y ON ....`
KM
I'd have given you an upvote but bot when you use the old implicit join syntax in your examples as that is a very poor programming practice. Plus you are showing cross joins which I doubt the user wants and these types of accidental cross joins are one of the reason why this syntax was replaced 18 years ago with the explicit join syntax.
HLGEM
The code snippets above are just to illustrate the issue at hand.
Hassan Syed