IT박스

외래 키 명명 체계

itboxs 2020. 6. 23. 07:58

외래 키 명명 체계


처음으로 외래 키 작업을 시작했으며 표준 명명 체계가 있는지 궁금합니다.

이러한 테이블이 주어지면 :

task (id, userid, title)
note (id, taskid, userid, note);
user (id, name)

작업에 메모가있는 경우 사용자는 작업을 소유하며 사용자는 메모를 작성합니다.

이 상황에서 세 개의 외래 키는 어떻게 명명됩니까? 아니면 전혀 문제가되지 않습니까?

업데이트 :이 질문은 필드 이름이 아닌 외래 키 이름에 관한 것입니다!


SQL Server의 표준 규칙은 다음과 같습니다.

FK_ForeignKeyTable_PrimaryKeyTable

예를 들어 메모와 작업의 핵심은 다음과 같습니다.

FK_note_task

작업과 사용자 사이의 핵심은 다음과 같습니다.

FK_task_user

이를 통해 어떤 테이블이 키와 관련되어 있는지 한 눈에 볼 수 있으므로 특정 테이블 (첫 번째 테이블)이 어떤 테이블 (두 번째 테이블)에 의존하는지 쉽게 볼 수 있습니다. 이 시나리오에서 전체 키 세트는 다음과 같습니다.

FK_task_user
FK_note_task
FK_note_user

따라서 작업이 사용자에 의존하고 메모가 작업과 사용자에 의존한다는 것을 알 수 있습니다.


구분 기호로 두 개의 밑줄 문자를 사용합니다.

fk__ForeignKeyTable__PrimaryKeyTable 

테이블 이름에 때때로 밑줄 문자가 포함되기 때문입니다. 데이터 요소의 이름은 종종 밑줄 문자를 포함하기 때문에 제약 조건의 명명 규칙을 따릅니다.

CREATE TABLE NaturalPersons (
   ...
   person_death_date DATETIME, 
   person_death_reason VARCHAR(30) 
      CONSTRAINT person_death_reason__not_zero_length
         CHECK (DATALENGTH(person_death_reason) > 0), 
   CONSTRAINT person_death_date__person_death_reason__interaction
      CHECK ((person_death_date IS NULL AND person_death_reason IS NULL)
              OR (person_death_date IS NOT NULL AND person_death_reason IS NOT NULL))
        ...

어때요 FK_TABLENAME_COLUMNNAME?

K EEP I t S imple S tupid 때 이제까지 가능.


나는 보통 PK라는 id를 남겨두고 다른 테이블에서 FK를 명명 할 때 테이블 이름과 키 열 이름을 연결합니다. 일부 데이터베이스는 대 / 소문자를 구분하지 않고 어쨌든 모든 대문자 또는 소문자 이름을 반환하기 때문에 낙타 케이싱에 신경 쓰지 않습니다. 어쨌든, 내 테이블 버전은 다음과 같습니다.

task (id, userid, title);
note (id, taskid, userid, note);
user (id, name);

행은 내가 유지하는 객체 중 하나를 나타 내기 때문에 표 이름을 단수로 지정합니다. 이러한 규칙 중 많은 부분이 개인 취향입니다. 나는 다른 사람의 협약을 채택하는 것보다 협약을 선택하고 항상 사용하는 것이 더 중요하다고 제안합니다.


SQL Server에 관한 Microsoft의 참고 사항 :

FOREIGN KEY 제약 조건은 다른 테이블의 PRIMARY KEY 제약 조건에만 연결될 필요는 없습니다. 다른 테이블에서 UNIQUE 제약 조건의 열을 참조하도록 정의 할 수도 있습니다.

따라서 기존의 기본 / 외국 관계 용어 대신 종속성을 설명하는 용어를 사용합니다.

종속 (자식) 테이블 에서 비슷한 이름의 열 (들) 독립 (부모) 테이블 의 PRIMARY KEY를 참조 할 때 열 이름을 생략합니다.

FK_ChildTable_ParentTable

다른 열을 참조하거나 열 이름이 두 테이블간에 다르거 나 명시 적으로 나타납니다.

FK_ChildTable_childColumn_ParentTable_parentColumn

이것은 아마도 과잉 살상이지만 나를 위해 일합니다. VLDB를 다룰 때 특히 도움이됩니다. 나는 다음을 사용한다 :

CONSTRAINT [FK_ChildTableName_ChildColName_ParentTableName_PrimaryKeyColName]

Of course if for some reason you are not referencing a primary key you must be referencing a column contained in a unique constraint, in this case:

CONSTRAINT [FK_ChildTableName_ChildColumnName_ParentTableName_ColumnInUniqueConstaintName]

Can it be long, yes. Has it helped keep info clear for reports, or gotten me a quick jump on that the potential issue is during a prod-alert 100% would love to know peoples thoughts on this naming convention.


My usual approach is

FK_ColumnNameOfForeignKey_TableNameOfReference_ColumnNameOfReference

Or in other terms

FK_ChildColumnName_ParentTableName_ParentColumnName

This way I can name two foreign keys that reference the same table like a history_info table with column actionBy and actionTo from users_info table

It will be like

FK_actionBy_usersInfo_name - For actionBy
FK_actionTo_usersInfo_name - For actionTo

Note that:

I didn't include the child table name because it seems common sense to me, I am in the table of the child so I can easily assume the child's table name. The total character of it is 26 and fits well to the 30 character limit of oracle which was stated by Charles Burns on a comment here

Note for readers: Many of the best practices listed below do not work in Oracle because of its 30 character name limit. A table name or column name may already be close to 30 characters, so a convention combining the two into a single name requires a truncation standard or other tricks. – Charles Burns


Based on the answers and comments here, a naming convention which includes the FK table, FK field, and PK table (FK_FKTbl_FKCol_PKTbl) should avoid FK constraint name collisions.

So, for the given tables here:

fk_task_userid_user
fk_note_userid_user

So, if you add a column to track who last modified a task or a note...

fk_task_modifiedby_user
fk_note_modifiedby_user

Try using upper-cased Version 4 UUID with first octet replaced by FK and '_' (underscore) instead of '-' (dash).

E.g.

  • FK_4VPO_K4S2_A6M1_RQLEYLT1VQYV
  • FK_1786_45A6_A17C_F158C0FB343E
  • FK_45A5_4CFA_84B0_E18906927B53

Rationale is the following

  • Strict generation algorithm => uniform names;
  • Key length is less than 30 characters, which is naming length limitation in Oracle (before 12c);
  • If your entity name changes you don't need to rename your FK like in entity-name based approach (if DB supports table rename operator);
  • One would seldom use foreign key constraint's name. E.g. DB tool usually shows what the constraint applies to. No need to be afraid of cryptic look, because you can avoid using it for "decryption".

If you aren't referencing your FK's that often and using MySQL (and InnoDB) then you can just let MySQL name the FK for you.

At a later time you can find the FK name you need by running a query.

참고URL : https://stackoverflow.com/questions/199498/foreign-key-naming-scheme