기본 키 / 외래 키 명명 규칙 [닫힘]
개발 그룹에서는 기본 및 외래 키의 명명 규칙에 대해 격렬한 논쟁이 있습니다. 우리 그룹에는 기본적으로 두 가지 학파가 있습니다.
1:
Primary Table (Employee)
Primary Key is called ID
Foreign table (Event)
Foreign key is called EmployeeID
또는
2 :
Primary Table (Employee)
Primary Key is called EmployeeID
Foreign table (Event)
Foreign key is called EmployeeID
어떤 열에도 테이블 이름을 복제하지 않는 것을 선호합니다 (따라서 위의 옵션 1을 선호합니다). 개념적으로는 속성 이름에 개체 이름을 사용하지 않는 다른 언어의 권장 사례와 일치합니다. 외래 키의 이름을 지정하면 EmployeeID
(또는 Employee_ID
더 좋을 수도 있음) 독자에게 그것이 테이블 의 ID
열 임을 알 수 있다고 생각합니다 Employee
.
다른 일부는 열 이름이 데이터베이스 전체에서 동일하도록 테이블 이름이 접두어로 붙은 기본 키의 이름을 지정하는 옵션 2를 선호합니다. 그 점을 알지만 이제는 기본 키와 외래 키를 시각적으로 구분할 수 없습니다.
또한, 나는 당신이 개체와 그 개체의 속성이나 속성으로 컬럼과 테이블을 생각하면, 당신은의 ID 속성으로 생각하기 때문에, 열 이름에 테이블 이름을 가지고 중복 생각 Employee
하지 EmployeeID
직원 의 속성. 나는 그의 것을 내 동료에게 가지 않는다 PersonAge
또는 PersonGender
이다. 나는 그에게 그의 나이가 무엇인지 묻습니다.
그래서 제가 말했듯이, 그것은 격렬한 논쟁이며 우리는 그것에 대해 계속해서 계속합니다. 새로운 관점을 얻고 싶습니다.
별로 중요하지 않습니다. 나는 선택 1과 선택 2 사이에 실질적인 차이가있는 시스템을 본 적이 없습니다.
Jeff Atwood는이 주제에 대한 훌륭한 기사를 가지고있었습니다. 기본적으로 사람들은 자신이 잘못 증명할 수없는 주제에 대해 가장 격렬하게 토론하고 논쟁합니다. 또는 다른 각도에서, 필리 버스터 스타일의 지구력 기반 최후의 주장을 통해서만 이길 수있는 주제.
하나를 선택하고 실제로 코드에 영향을 미치는 문제에 집중하도록 지시하십시오.
편집 : 재미를 원한다면 재귀 테이블 참조에 대해 방법이 우수한 이유를 길게 지정하십시오.
두 열의 이름이 두 테이블 모두에서 동일한 경우 (컨벤션 # 2) SQL에서 USING 구문을 사용하여 입력 및 상용구 노이즈를 줄일 수 있습니다.
SELECT name, address, amount
FROM employees JOIN payroll USING (employee_id)
관례 # 2를 찬성하는 또 다른 주장은 이것이 관계형 모델 이 설계된 방식이라는 것 입니다.
각 열의 중요성은 해당 도메인의 이름으로 레이블을 지정하여 부분적으로 전달됩니다.
신청 방법에 따라 다릅니다. ORM을 사용하거나 테이블을 디자인하여 개체를 나타내는 경우 옵션 1이 적합 할 수 있습니다.
데이터베이스를 자체 레이어로 코딩하고 싶습니다. 나는 모든 것을 제어하고 앱은 저장 프로 시저 만 호출합니다. 특히 조인 된 테이블이 많고 많은 열이 반환되는 경우 완전한 열 이름을 가진 결과 집합을 갖는 것이 좋습니다. 이 유형의 응용 프로그램에서는 옵션 2를 좋아합니다. 조인에서 열 이름이 일치하는 것을보고 싶습니다. 나는 그들이 일치하지 않는 오래된 시스템에서 일했고 그것은 악몽이었습니다.
Neither convention works in all cases, so why have one at all? Use Common sense...
e.g., for self-referencing table, when there are more than one FK column that self-references the same table's PK, you HAVE to violate both "standards", since the two FK columns can't be named the same... e.g., EmployeeTable with EmployeeId PK, SupervisorId FK, MentorId Fk, PartnerId FK, ...
I agree that there is little to choose between them. To me a much more significant thing about either standard is the "standard" part.
If people start 'doing their own thing' they should be strung up by their nethers. IMHO :)
Have you considered the following?
Primary Table (Employee)
Primary Key is PK_Employee
Foreign table (Event)
Foreign key is called FK_Employee
The convention we use where I work is pretty close to A, with the exception that we name tables in the plural form (ie, "employees") and use underscores between the table and column name. The benefit of it is that to refer to a column, it's either "employees _ id" or "employees.id", depending on how you want to access it. If you need to specify what table the column is coming from, "employees.employees _ id" is definitely redundant.
If you are looking at application code, not just database queries, some things seem clear to me:
Table definitions usually directly map to a class that describes one object, so they should be singular. To describe a collection of an object, I usually append "Array" or "List" or "Collection" to the singular name, as it more clearly than use of plurals indicates not only that it is a collection, but what kind of a collection it is. In that view, I see a table name as not the name of the collection, but the name of the type of object of which it is a collection. A DBA who doesn't write application code might miss this point.
The data I deal with often uses "ID" for non-key identification purposes. To eliminate confusion between key "ID"s and non-key "ID"s, for the primary key name, we use "Key" (that's what it is, isn't it?) prefixed with the table name or an abbreviation of the table name. This prefixing (and I reserve this only for the primary key) makes the key name unique, which is especially important because we use variable names that are the same as the database column names, and most classes have a parent, identified by the name of the parent key. This also is needed to make sure that it is not a reserved keyword, which "Key" alone is. To facilitate keeping key variable names consistent, and to provide for programs that do natural joins, foreign keys have the same name as is used in the table in which they are the primary key. I have more than once encountered programs which work much better this way using natural joins. On this last point, I admit a problem with self-referencing tables, which I have used. In this case, I would make an exception to the foreign key naming rule. For example, I would use ManagerKey as a foreign key in the Employee table to point to another record in that table.
I like convention #2 - in researching this topic, and finding this question before posting my own, I ran into the issue where:
I am selecting * from a table with a large number of columns and joining it to a second table that similarly has a large number of columns. Both tables have an "id" column as the primary key, and that means I have to specifically pick out every column (as far as I know) in order to make those two values unique in the result, i.e.:
SELECT table1.id AS parent_id, table2.id AS child_id
Though using convention #2 means I will still have some columns in the result with the same name, I can now specify which id I need (parent or child) and, as Steven Huwig suggested, the USING
statement simplifies things further.
I've always used userId as a PK on one table and userId on another table as a FK. 'm seriously thinking about using userIdPK and userIdFK as names to identify one from the other. It will help me to identify PK and FK quickly when looking at the tables and it seems like it will clear up code when using PHP/SQL to access data making it easier to understand. Especially when someone else looks at my code.
I use convention #2. I'm working with a legacy data model now where I don't know what stands for in a given table. Where's the harm in being verbose?
How about naming the foreign key
role_id
where role is the role the referenced entity has relativ to the table at hand. This solves the issue of recursive reference and multiple fks to the same table.
In many cases will be identical to the referenced table name. In this cases it becomes identically to one of your proposals.
In any case havin long arguments is a bad idea
"Where in "employee INNER JOIN order ON order.employee_id = employee.id" is there a need for additional qualification?".
There is no need for additional qualification because the qualification I talked of is already there.
"the reason that a business user refers to Order ID or Employee ID is to provide context, but at a dabase level you already have context because you are refereing to the table".
Pray, tell me, if the column is named 'ID', then how is that "refereing [sic] to the table" done exactly, unless by qualifying this reference to the ID column exactly in the way I talked of ?
참고URL : https://stackoverflow.com/questions/1369593/primary-key-foreign-key-naming-convention
'IT story' 카테고리의 다른 글
React의 JSX 구문에서 이중 중괄호의 목적은 무엇입니까? (0) | 2020.09.07 |
---|---|
C #에서 클래스의 소멸자와 Finalize 메서드의 차이점은 무엇입니까? (0) | 2020.09.07 |
while 루프 내에서 bash에서 입력 읽기 (0) | 2020.09.07 |
CORS-httprequest를 어떻게 '프리 플라이트'합니까? (0) | 2020.09.07 |
Django 모델 "명시적인 app_label을 선언하지 않습니다" (0) | 2020.09.07 |