부트캠프 기록/Serction2

[데이터베이스] SQL DB Schema

bbangduck 2022. 10. 7. 16:08

▶Schema 정의

데이터베이스에서 데이터가 구성되는 방식과 서로 다른 엔티티 간의 관계에 대한 설명

"데이터베이스의 청사진"

 

▶관계형 데이터베이스 키워드

데이터, 테이블, 칼럼(필드), 레코드(튜플), 키 

 

▶관계종류

1:1 , 1: N, N:M 관계

자기 참조 (1:N 관계와 유사)

한 개/여러 개 로 구별 가능

 

 

▶인스타그램 스키마 디자인

 

교육 전 (figma 이용)

교육 후(https://dbdiagram.io/ 이용) 

다대다 관계는 조인 테이블이 필수

follow_follower 테이블 하나로 한 객체의 팔로우와 팔로잉을 모두 조회 가능

만약 post_likes나 post_comment의 user_Id를 posts에서 참조한다면 포스트를 올린 해당 유저의 아이디만 참조할 수 있음

 

더보기
CREATE TABLE `users` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(50),
  `password` varchar(50)
);

CREATE TABLE `posts` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `image` blob,
  `message` text,
  `created_at` datetime DEFAULT (CURRENT_TIMESTAMP),
  `total_likes` INT DEFAULT 0,
  `total_comments` INT DEFAULT 0,
  `user_id` INT
);

CREATE TABLE `post_comments` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `comment` varchar(255),
  `created_at` datetime DEFAULT (CURRENT_TIMESTAMP),
  `user_id` INT,
  `post_id` INT
);

CREATE TABLE `post_likes` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `created_at` datetime DEFAULT (CURRENT_TIMESTAMP),
  `user_id` INT,
  `post_id` INT
);

CREATE TABLE `follow_follower` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `follower_id` INT,
  `user_id` INT
);

CREATE TABLE `posts_hashtags` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `hashtag_id` INT,
  `post_id` INT
);

CREATE TABLE `hashtags` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `name` char(50)
);

ALTER TABLE `posts` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `follow_follower` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `post_comments` ADD FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`);

ALTER TABLE `post_comments` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `post_likes` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `post_likes` ADD FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`);

ALTER TABLE `posts_hashtags` ADD FOREIGN KEY (`hashtag_id`) REFERENCES `hashtags` (`id`);

ALTER TABLE `posts_hashtags` ADD FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`);

ALTER TABLE `follow_follower` ADD FOREIGN KEY (`follower_id`) REFERENCES `users` (`id`);

 

▶query문과 statement는 다름