简体   繁体   中英

selecting data from two different columns in one table that point to the same column in another table

I have two tables which i have summarised below just to keep the question simple.

The first table has a list of tasks - the two important columns to note is the id number "idTask" and the name of that task "sgItemName". It looks like this

idTask sgItemName
1 Do this
2 Do that
3 Then this
4 Then that

The second table lists each task that has a precedent task that needs to be completed before it, and then what that precedent is - the two important columns to note is the parent task "fkidParentTask" and the precedent task "fkidPrecedentTask". Some tasks might have multiple precedents. It looks like this

fkidParentTask fkidPrecedentTask
2 1
3 2
3 1
4 3
4 2

What i would like to achieve is a select query that gives me an output as follows

Parent Task Precedent Task
Do that Do this
Then this Do that
Then this Do this
Then that Then this
Then that Do that

I'm still learning SQL but I cannot get this to work at all? Can someone help me?

Thank you in advance!

You need to use the table1 multiple times in the join as follows:

select t11.sgItemName as ParentTask,
       t12.sgItemName as PrecedentTask
  from table2 t2 
  join table1 t11 on t2.fkidParentTask = t1.idTask
  join table1 t12 on t2.fkidPrecedentTask = t1.idTask

For SQL-Server:

   Select tm1.sgItemName as [Parent Task] , tm2.sgItemName [Precedent Task]
    from ParentPrecedentMapping ppm
    join Taskmaster tm1 on ppm.fkidParenttask = tm1.idtask
    join Taskmaster tm2 on ppm.fkidPrecedenttask = tm2.idtask

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM