Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extracting values from same field different row using different where statements

Status
Not open for further replies.

sunbase

Technical User
Jun 18, 2009
15
0
0
GB
I have a table called `employment` that contains two INT references named `employer` and `employee`. As a person can be either or both I have a single table named `personnel`.

I am trying to construct a query that displays

personnel.name as `employer` where employment.employer=personnel.id

AND

personnel.name as `employee` where employment.employee=personnel.id

so it extracts multiple details from one table with different where conditions and applying different alias values

Very very new to sql so my head is starting to spin

For example my personnel file:

id name
1 David
2 Simon
3 Michael
4 Tony
5 Paul

employment file:

Job 1, Title "housea" employer 2 employee 5 - I would be looking to return the values
[1][housea][Simon][Paul]

Job 2, Title "houseb" employer 1 employee 2 - I would be looking to return the values
[1][houseb][David][Simon]

If you understand what I am trying to do can you please help
 
A backtick as name delimiter always points me to MySQL, are you posting in the right forum section?

Aside of MSSQL or MySQL, the general approach to joining a table with two foreign keys (employee, employer) both pointing to one table (personnel) is doing two joins to it, joining with a table alias name, eg

Code:
Select employment.job, employment.title, employment.employee, employees.name as employeename, employment.employer, employers.name as employername
from employment 
left join [b]personnel as employees[/b] on employees.id = employment.employee
left join [b]personnel as employers[/b] on employers.id = employment.employer

Bye, Olaf.
 
Doesn't it work for you? Too many result columns, wrongly named? That's a no brainer, simply remove unwanted result columns from code line 1 and/or rename them, too. The main ingredient is the double joining of personnel.

Bye, Olaf.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top