inblog logo
|
vosw1
    Spring

    Join - 기본 셋팅

    Feb 01, 2024
    Join - 기본 셋팅

    💡
    ctrl + shift + enter : 전체 실행
    ctrl + enter : 부분 실행
     
    보기를 보고 만들 때 순서 확인하고 INSERT하기!
    실행 후 성공 실패 여부 확인하면서 하기!
    스칼라로 다 쪼개야함 → 자바와 달리 DB는 데이터 타입 1개로만 받을 수 있기 때문
     
    notion image
    notion image
    notion image
    create database metadb; use metadb; CREATE TABLE user_tb( id int primary key auto_increment, username varchar(20), password varchar(20), profile_url varchar(100), email varchar(100), createDate TIMESTAMP ); CREATE TABLE image_tb( id int primary key auto_increment, photo_url varchar(100), content varchar(1000), user_id int, createDate TIMESTAMP ); CREATE TABLE love_tb( id int primary key auto_increment, image_id int, user_id int, createDate TIMESTAMP ); CREATE TABLE reply_tb( id int primary key auto_increment, content varchar(100), user_id int, image_id int, createDate TIMESTAMP );
    notion image
     
    INSERT INTO user_tb(username, password, profile_url, email, createDate) VALUES('ssar', '1234' , '/profile/1.jpg', 'ssar@nate.com', now()); INSERT INTO user_tb(username, password, profile_url, email, createDate) VALUES('cos', '1234' , '/profile/2.jpg', 'cos@nate.com', now()); INSERT INTO user_tb(username, password, profile_url, email, createDate) VALUES('love', '1234' , '/profile/3.jpg', 'love@nate.com', now()); INSERT INTO image_tb(photo_url, content, user_id, createDate) values('/image/1.jpg', '여행사진', 1, now()); INSERT INTO image_tb(photo_url, content, user_id, createDate) values('/image/2.jpg', '강아지사진', 1, now()); INSERT INTO image_tb(photo_url, content, user_id, createDate) values('/image/3.jpg', '친구사진', 2, now()); INSERT INTO love_tb(user_id, image_id, createDate) values(1, 1, now()); INSERT INTO love_tb(user_id, image_id, createDate) values(2, 2, now()); INSERT INTO love_tb(user_id, image_id, createDate) values(2, 3, now()); INSERT INTO love_tb(user_id, image_id, createDate) values(3, 3, now()); INSERT INTO reply_tb(content, user_id, image_id, createDate) VALUES('재밌겠다~~!', 1, 1, now());
    select * from user_tb; select * from image_tb; select * from love_tb; select * from reply_tb;
     
    notion image
    notion image
    notion image
    notion image
     

    연습하기

     
    • 여행사진을 올린 사람의 아이디를 알고 싶을 때
    use metadb; select * from user_tb; select * from image_tb; select user_id from image_tb where content = '여행사진'; select username from user_tb where id = (select user_id from image_tb where content = '여행사진');
    notion image
     
    • 가장 회원 가입을 늦게 한 유저 네임을 알고 싶을 때
    select max(id) from user_tb;
     
    • 이미지 옆에 좋아요 갯수를 알고 싶을 때
    그룹함수
     
    일반서브쿼리는 WHERE절에 걸림
     
    세로로 붙이고 싶을때
    셀렉트와 셀릭트를 유니온 올
    유니온이 집합을 하는 것 그래서 컬럼 명이 됨
    컬럼명이 같아야 가능 하나라도 다르면 불가
     
    select 1, count(*) from love_tb where image_id = 1 union all select 2, count(*) from love_tb where image_id = 2 union all select 3, count(*) from love_tb where image_id = 3;
    notion image
     
    select 1 image_id, count(*) love_count from love_tb where image_id = 1 union all select 2, count(*) from love_tb where image_id = 2 union all select 3, count(*) from love_tb where image_id = 3;
    notion image
    이미지 아이디는 이미지를 표시할 수 없음
    이미지 테이블가면 실제 이미지가 잇는 컬럼이 있음
     
    데이터베이스는 실행되는 결과를 가지고 정보를 만들어냄
    Mylove
    N
    image_id
    love_count
    1
    1
    2
    1
    3
    2
     
     
    notion image

    1. 랜덤 엑세스

    디비에서 프라이머리 키를 만들면 인덱스를 만듦
    인덱스 = 목차
    목차를 보고 다이렉트 엑세스 함
     

    2. 드라빙은 풀스캔

    조인하기전에 드라이빙의 행을 줄이면 퍼포먼스가 좋아짐
    한번만 가서 인덱스 스캔하면 끝남
     

    3. 인라인뷰 (FROM에 걸림)

    인라인 뷰(Inline View)는 데이터베이스에서 쿼리를 실행할 때 사용되는 개념 중 하나입니다. 이는 하나의 SELECT 문 안에서 파생된 테이블을 나타냅니다. 일반적으로 서브쿼리라고도 불리며, 주로 복잡한 쿼리나 필요한 부분집합을 만들어 사용할 때 활용됩니다.
    장점 심플하게 만들어줌
    별칭 쓸때 좋음
    select id, username, substr(email, 1, 4) my_email from user_tb where my_email = 'ssar';
    where이 만들어지기 전에 별칭이 만들어져서 안됨
    where을 못쓰니까 순서를 바꿔치기함
     
    select * from ( select id, username, substr(email, 1, 4) my_email from user_tb ) love_tb where my_email = 'ssar';
    notion image
     

    4. inner join

    select * from ( select 1 image_id, count(*) love_count from love_tb where image_id = 1 union all select 2, count(*) from love_tb where image_id = 2 union all select 3, count(*) from love_tb where image_id = 3 ) lo inner join image_tb im on im.id = lo.image_id;
    notion image
    select im.* , 3 love_count from image_tb im;
     
    notion image
     

    5. 스칼라 서브 쿼리(SELECT에 걸림)

    프로젝션 절에 서브쿼리 쓰는 것
    커서를 한칸 내리고 프로젝션하는 것을 셀렉트로 해서 총 포문이 3번 돌게 됨
    *는 전체를 프로젝션하는 것
     
    반드시 결과로 하나의 행이여야함
     
    스칼라 서브 쿼리로 러브 카운터 넣기
    select im.*, 3 love_count from image_tb im;
    notion image
     
    select *, (select username from user_tb where id = 1) from image_tb;
    notion image
    select * from love_tb where image_id = 3;
    notion image
    select *, (select count(*) from love_tb where image_id = 3) from image_tb;
    notion image
    notion image
    notion image
    캐싱함
     

    6.그룹핑(Grouping) : 그룹으로 묶음

    • DB : 가로연산은 되는데 세로 연산이 안됨
    • GROUP BY는 세로 연산이 가능함
    • 그룹핑 > 무조건 찌끄러뜨림 > 셀렉트
    • 그룹핑을 하면 무조건 찌끄러뜨려야함 아니면 실행 안됨!
    문법오류! → 무조건 그룹함수가 필요함
    ex) 그룹핑을 하는 이유는 같은 나이 때 키 평균을 구하고 싶을 때
    75끼리 찌끄러뜨리는 것이 그룹바이 → 행의 갯수를 맞춰야 함
    그룹함수를 쓰면 찌그러지는데
    안 찌그러지면 행의 갯수가 안 맞으니까 같이 찌끄러뜨리는 것
     

    7. SQL 쿼리의 실행 순서

    (1) FROM 절 수행
    : 데이터를 가져올 대상 테이블이나 서브 쿼리로부터 데이터를 가져옴
    (2) WHERE 절 수행
    : 필요한 조건에 따라 데이터를 필터링
    (3) GROUP BY 절 수행
    : 그룹핑에 사용할 기준 열(Column)을 기준으로 데이터를 그룹화
    일종의 카테고리를 만들어 그 안에서 집계 함수를 사용할 수 있음
    → 세로의 데이터를 동일하게 만들어야 함
    (4) HAVING 절 수행
    : GROUP BY 이후 그룹화된 결과에 대한 조건을 적용
    HAVING은 WHERE와 유사하지만, GROUP BY 이후에 수행
    (5) SELECT 절 수행
    : 최종 결과를 출력할 열을 선택, 필요한 계산이나 집계 함수를 적용
    Projection : SELECT 절을 사용하여 데이터를 검색하거나 가공하는 과정
    정렬 전에 수행됨
    (6) ORDER BY 절 수행
    : 필요한 경우 결과를 정렬 / 정렬은 항상 마지막
     
     
    Share article

    vosw1

    RSS·Powered by Inblog