Using Foreign Keys, but showing another column (not id) during a query in MySQL

时间:2015-05-24 21:25:46

标签: mysql database foreign-keys rdbms

I have a question regarding foreign keys. I have searched for the answer and was unable to location one.

I have a table 'projects' that has the column 'owner_id' which references 'managers.owner_id' as a foreign key.

Would it be possible to reference 'managers.owner_id' as a foreign key, but show the column 'managers.full_name'? When I run a SELECT query against the 'projects' table, I want to see the manager's name to come up and not the manager's id.

If it is possible, is this normally done with the SELECT command or can I configure it when I CREATE/ALTER the 'projects' table?

I am fairly new with MySQL, thank you for your time and patience! If what I'm asking seems insane, I wouldn't mind hearing what your thoughts are or if you have any other suggestions.

1 个答案:

答案 0 :(得分:0)

You just need to join the tables and select the fields that you want e.g.

SELECT projects.project_name, managers.full_name
FROM projects
INNER JOIN managers on projects.owner_id = managers.owner_id

If there are projects where the owner_id is NULL but you still want to list it then use a LEFT JOIN instead.