Question

I have a problem with a question I don't fully understand. Was wondering if anyone could help me with it, Or at least help me understand.

Lets say we have a table 'Jobs' with 2 columns job numbers 'jobnum', and employee numbers 'empnum'

Table: Jobs
---------------------------------------
|      jobnum      |      empnum      |
---------------------------------------
|       125        |       4785       |
|       100        |       4200       |
|       305        |       4001       |
|       125        |       4224       |
|       102        |       4840       |
|       100        |       4224       |
|       107        |       4534       |
|       255        |       4200       |
|       208        |       4224       |
|       301        |       4785       |
---------------------------------------

I like the job that was done at a certain work site, lets take jobnum '125', and want to know the other jobnums of the same employees. It shows that two people worked on jobnum 125. '4224' and '4785'. How would I write a SQL query that would output the jobnums of the same people that did job '125'. I am supposed to use Join query and cannot use sub-query

I understand how I would do it using a sub-query but don't know how I would going about it using a Join. I am assuming I would do a self join? Perhaps I don't fully understand Joins =/

Was it helpful?

Solution

Using Join:

Select 
    j1.jobnum,
    j1.empnum
From jobs j1
    Join jobs j2
        On j1.empnum = j2.empnum
Where j2.jobnum = 125

The query says "Give me all the records from jobs (j1) that have the same empnum as any record in jobs (j2) which has a jobnum of 125. That's the self-join that you're looking for.

OTHER TIPS

This is a generic solution

SELECT T1.* 

 JOBS T1 
INNER JOIN  JOBS T2

 ON( T1.jobnum=T2.jobnum AND T1.empnum<> T2.empnum)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top