Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reference a single table multiple times in the same query?

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

like image 412
masoud ramezani Avatar asked Feb 24 '10 13:02

masoud ramezani


People also ask

How do I reference the same table twice in SQL?

You use a single table twice in a query by giving it two names, like that. The aliases are often introduced with the keyword AS. You also normally specify a join condition (for without it, you get the Cartesian Product of the table joined with itself). For preference you use the explicit JOIN notation.

Which operator is used to give multiple values for a single field at a time?

The IN operator allows you to specify multiple values in a WHERE clause.


2 Answers

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
like image 86
Sparky Avatar answered Sep 23 '22 01:09

Sparky


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
like image 22
Aaron Avatar answered Sep 23 '22 01:09

Aaron