Can a foreign key act as a primary key?

前端 未结 2 686
走了就别回头了
走了就别回头了 2020-12-05 07:44

I\'m currently designing a database structure for our team\'s project. I have this very question in mind currently: Is it possible to have a foreign key act as a primary key

2条回答
  •  臣服心动
    2020-12-05 08:11

    Of course. This is a common technique known as supertyping tables. As in your example, the idea is that one table contains a superset of entities and has common attributes describing a general entity, and other tables contain subsets of those entities with specific attributes. It's not unlike a simple class hierarchy in object-oriented design.

    For your second question, one table can have two columns which are separately foreign keys to the same other table. When the database builds the query, it joins that other table twice. To illustrate in a SQL query (not sure about MySQL syntax, I haven't used it in a long time, so this is MS SQL syntax specifically), you would give that table two distinct aliases when selecting data. Something like this:

    SELECT
        student_accounts.name AS student_name,
        counselor_accounts.name AS counselor_name
    FROM
        student_rec
        INNER JOIN user_accounts AS student_accounts
          ON student_rec.student_number = student_accounts.user_id
        INNER JOIN user_accounts AS counselor_accounts
          ON student_rec.guidance_counselor_id = counselor_accounts.user_id
    

    This essentially takes the student_rec table and combines it with the user_accounts table twice, once on each column, and assigns two different aliases when combining them so as to tell them apart.

提交回复
热议问题