250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- glob
- inplace()
- 오버라이딩
- items()
- fnmatch
- decode()
- 파이썬
- __getitem__
- fileinput
- locals()
- zipfile
- HTML
- shuffle()
- JS
- choice()
- Database
- CSS
- count()
- mro()
- __annotations__
- __len__
- View
- node.js
- shutil
- randrange()
- __sub__
- discard()
- MySQL
- remove()
- MySqlDB
Archives
- Today
- Total
흰둥이는 코드를 짤 때 짖어 (왈!왈!왈!왈!왈!왈!왈!왈!왈!왈!왈!)
(MySQL) 기초 문법(외래키, 조인) 본문
728x90
반응형
member 테이블
select * from member;
profile 테이블 생성
create table profile(
userid varchar(20) not null,
height double,
weight double,
blood varchar(10),
mbti varchar(10),
foreign key(userid) references member(userid)
);
profile의 userid를 member의 userid와 외래키로 묶었다.
insert into profile values('ryuzy', 180, 70, 'AAA', 'ISTP'); # Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`kdt`.`profile`, CONSTRAINT `profile_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `member` (`userid`))
insert into profile values('apple', 163, 50, 'B', 'ESFP');
insert into profile values('banana', 161, 46, 'AB', 'INTP');
insert into profile values('grapes', 173, 65, 'O', 'ENTP');
insert into profile values('melon', 155, 45, 'B', 'INFP');
insert into profile values('orange', 176, 68, 'A', 'ISFP');
만약 userid를 member userid에 없는 값으로 입력할 경우 에러가 발생한다.
select * from profile;
조인
# select 필드명1, 필드명2 ... from 테이블1 [inner, left, right] join 테이블2 on 테이블1.연결할필드 = 테이블2.연결할필드;
inner 조인
- 조인하는 테이블의 on 절의 조건이 일치하는 결과만 출력
- join, inner join, cross join 모두 같은 의미로 사용됨
select userid, username, hp, height, weight, mbti from member
inner join
profile on member.userid = profile.userid; # Error Code: 1052. Column 'userid' in field list is ambiguous
select m.userid, m.username, m.hp, p.height, p.weight, p.mbti from member as m
inner join
profile as p on m.userid = p.userid;
조인 할 경우 컬럼명 앞에 어떤 테이블에서 가져오는지 표시 해주어야 한다.
left/right outer 조인
- 두 테이블이 조인 될 때 왼쪽/오른쪽을 기준으로 했느냐에 따라 기준 테이블의 것을 모두 출력
- outer join은 조인하는 테이블의 on 절의 조건 중 한쪽의 데이터를 모두 가져옴
- left outer join, right outer join, full outer join 이렇게 3가지가 있음
- full outer join은 거의 사용하지 않음
select m.userid, m.username, m.hp, p.height, p.weight, p.mbti from member as m
left outer join
profile as p on m.userid = p.userid;
select m.userid, m.username, m.hp, p.height, p.weight, p.mbti from member as m
right outer join
profile as p on m.userid = p.userid;
inner는 조건에 전부 일치하는 데이터를, outer는 기준(left, right)이 되는 테이블의 데이터는 전부 가져오고 일치하는 상대 테이블 데이터를 가져온다. 만약 상대 테이블에 데이터가 없을 경우 null값으로 가져온다.
728x90
반응형
'MySQL' 카테고리의 다른 글
(MySQL) 기초 문법(auto_increment) (0) | 2023.03.20 |
---|---|
(MySQL) 정규화 (0) | 2023.03.20 |
(MySQL) 기초 문법(Read, 연산자) (0) | 2023.03.16 |
(MySQL) 기초 문법(database, Create, Update, Delete) (0) | 2023.03.16 |
(MySQL) MySQL설치 및 기초 (0) | 2023.03.15 |
Comments