MySQL 기초

[SQL] 관계가 있는 2개의 테이블을 하나로 합치는 방법

jasonshin 2021. 12. 8. 15:54

1)

tabel 2개를 만든다.

 

2) 

2개의 table에서 합칠 컬럼(예: id)에 UN을 체크한 후 foreign keys를 설정한다.

 

3)

합치는 3가지 방법

1. Implicit Join
select * 
from customers, orders
where customers.id = orders.customer_id;

select * 
from orders, customers
where custumers.id = orders.customer_id;

2. Explicit Join
select * 
from orders
join customers
    on orders.customer_id = customers.id;

order by orders.order_date;

 

3. Left Join
select *
from customers
left join orders

    on customers.id= orders.customer_id;

 

customers, orders 테이블 2개 만들기

(예제)

 

insert into customers (first_name, last_name, email)
values ('Boy', 'George', 'george@gmail.com'),
('George', 'Michael', 'gm@gmail.com'),
    ('David', 'Bowie', 'david@gmail.com'),
    ('Blue', 'Steele', 'blue@gmail.com'),
    ('Bette', 'Davis', 'bette@aol.com');
    
insert into orders (order_date, amount, customer_id)
values ('2016/02/10', 99.99, 1),
('2017/11/11', 35.50, 1),
        ('2014/12/12', 800.67, 2),
        ('2015/01/03', 12.50, 2),
        ('1999/04/11', 450.25, 5);

select * from customers;
select * from orders;

-- customers 테이블에는 없는 고객 아이디로
-- orders 테이블에 정보를 입력하는 경우
insert into orders (order_date, amount, customer_id)
values ('2016/06/06', 33.67, 6);

select * from orders;
-- 유령 고객인데, orders 테이블에는 데이터가 들어간다.
-- 이렇게 되면 안된다!!

-- 따라서 테이블 생성시, 따로 처리해 줘야 하는 것이 있다.
-- 아까 집어넣은 것 일단 삭제
delete from orders
where id = 6;

select * from orders;

-- 테이블을 다시 만든다! foreign key를 설정한다.
create table orders ( 
id int auto_increment primary key,
    order_date date, 
    amount decimal(5,2), 
    customer_id int unsigned,
    foreign key(customer_id) references customers(id)
);

-- 유령회원 데이터 인서트문, 실행하면 이제는 에러난다.
insert into orders (order_date, amount, customer_id)
values ('2016/06/06', 33.67, 6);

-- Error Code : 1452
-- Cannot add or update a child row:
-- a foreign key constraint fails

select * from customers;
select * from orders;

반응형