월하점
월하점의 개발 공부 일지
월하점
전체 방문자
오늘
어제
  • 분류 전체보기 (96)
    • Back-end (3)
    • PROJECT (1)
    • CS (15)
      • Operating System (0)
      • Network (4)
      • Data Structure (7)
      • Algorithm (0)
      • Database (4)
    • Problem Solving (52)
    • Programming Languages (1)
      • Javascript (0)
      • Python (1)
      • JAVA (0)
    • Codestates BEB 4기 (7)
    • Blockchain (12)
    • Linux (2)
    • Git (1)
    • 잡다한 (2)

공지사항

인기 글

태그

  • SWEA
  • javascript
  • node.js
  • Python
  • 프로그래머스
  • 알고리즘
  • django
  • 네트워크
  • baekjoon
  • 자료구조
  • CS

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
월하점

월하점의 개발 공부 일지

  • HOME
  • GUEST
  • WRITE
CS/Database

[SQL] TestDome Solution - Users And Roles

2022. 9. 19. 21:45

문제

The following two tables are used to define users and their respective roles:

TABLE users
  id INTEGER NOT NULL PRIMARY KEY,
  userName VARCHAR(50) NOT NULL

TABLE roles
  id INTEGER NOT NULL PRIMARY KEY,
  role VARCHAR(20) NOT NULL

The users_roles table should contain the mapping between each user and their roles. Each user can have many roles, and each role can have many users.

Modify the provided SQL create table statement so that:

  • Only users from the users table can exist within users_roles.
  • Only roles from the roles table can exist within users_roles.
  • A user can only have a specific role once.
-- Modify only this SQL create table statement and nothing else
CREATE TABLE users_roles (
  userId INTEGER,
  roleId INTEGER
);

 

 

 

 

답안

CREATE TABLE users_roles (
  userId INTEGER NOT NULL,
  roleId INTEGER NOT NULL,
  CONSTRAINT user_fk FOREIGN KEY (userId) REFERENCES users(id)
  CONSTRAINT role_fk FOREIGN KEY (roleId) REFERENCES roles(id)
  PRIMARY KEY (userId, roleId)
);
  • Example case: Correct answer
  • Only users from users table can exist: Correct answer ⇒ NOT NULL, FK
  • Only roles from the roles table can exist: Correct answer ⇒ NOT NULL, FK
  • An user can only have a specific role once: Correct answer ⇒ PK 꼭 지정!

M:N 관계를 위한 조인 테이블을 만들기 위해 FK와 PK를 작성해야하는 문제였다.

저작자표시 비영리 변경금지 (새창열림)

'CS > Database' 카테고리의 다른 글

[SQL] TestDome Solution - Workers  (1) 2022.09.16
인스타그램 (Instagram) 스키마 디자인 - 관계형 데이터베이스로 설계  (0) 2022.05.25
트랜잭션의 특성 - ACID  (0) 2022.05.12
    'CS/Database' 카테고리의 다른 글
    • [SQL] TestDome Solution - Workers
    • 인스타그램 (Instagram) 스키마 디자인 - 관계형 데이터베이스로 설계
    • 트랜잭션의 특성 - ACID
    월하점
    월하점
    개발 공부를 기록합니다. 웹을 위주로 공부하며 컴퓨터과학 이론도 함께 정리할 계획입니다.

    티스토리툴바