Search code examples
sqldatabaseforeign-keysinner-join

Retrieve data using foreign key SQL


I am new to sql database and i have problem retrieving data using the foreign key

I have two tables,

1- Task list

task_number(PK)  task_name    members
1                UIRE         Ahmed
2                DES          Omar

2- task_history

task_number(FK)  history   Date
1                Started   07-03
1                Feedback  07-03
1                End       08-03

I have program associated with, which the user chooses the task_name from combo box and then he should see the history of the task

For example, using the mentioned above table the user shall choose "UIRE" from a choose list the program shall run a script to retrive the history data of the task "UIRE"

which is:

history   Date
Started   07-03
Feedback  07-03
End       08-03

I have tried inner join, and the normal select statement. But I didn't found a solution.

Any idea of solving this? Is it possible to retrieve data using foreign keys?


Solution

  • You're right. An inner join will do the search you want.

    For example:

    select
      h.*
    from task_list l
    join task_history h on h.task_number = l.task_number
    where l.task_name = 'UIRE' -- here's your filtering condition
    order by h.date -- this line is optional. Use it you want the ordering by date