1

I have 3 tables Manager, Lead, Trainee and the way they are related through a Relation table.

Attached image depicts the tables with saple rows and columns :

enter image description here

I need to get the Lead name and Trainee name for a given Manger.Id.

I have got the parameter name from the below query:

select 
    L.Name
from 
    Lead L, Manager M, Relation R 
where 
    R.PrimaryId = M.Id 
    and R.SecondaryId = L.Id 
    and M.Id = 'M101';

How do I get the trainee name apart from the lead name?

3
  • What do you want to achieve because according to your question you simply could just select Name from Trainee Commented Aug 24, 2015 at 9:34
  • @itwasntme I need to get the Lead name and Trainee name for a given Manger.Id. Commented Aug 24, 2015 at 9:36
  • Bad habits to kick : using old-style JOINs - that old-style comma-separated list of tables style was replaced with the proper ANSI JOIN syntax in the ANSI-92 SQL Standard (more than 20 years ago) and its use is discouraged Commented Aug 24, 2015 at 10:00

1 Answer 1

3

Your query is a bit clearer if you write it using joins instead of the old pre-1992 syntax:

select  L.Name
from    Manager M
join    Relation R 
on      R.PrimaryId = M.Id
join    Lead L
on      R.SecondaryId = L.Id
where   M.Id = 'M101'

You can add two new left joins to show the trainees per manager:

select  L.Name as lead
,       R.Name as trainee
from    Relation ML
join    Lead L
on      ML.SecondaryId = L.Id
left join
        Relation LT
on      LT.PrimaryId = L.Id
left join
        Trainee T
on      LT.SecondaryId = T.Id
where   ML.PrimaryId = 'M101'
Sign up to request clarification or add additional context in comments.

4 Comments

I ned the query to return two columns Lead name and Trainee name.
Added a query that does that. It only makes sense if there's no more than one trainee and no more than one lead per manager.
Yes , with this criteria the query works , but at an instance, a manager can have a lead without a trainee. The query gives wrong results for this criteria.
Aah, so the trainee is related to the lead, not the manager, I've updated the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.