[MySQL] JOIN : CROSS JOIN, INNER JOIN, LEFT JOIN, RIGHT JOIN / UNION
28 Nov 2021 -
1 minute read
create table customers(
customerid char(10) primary key,
name char(10) not null,
email char(20)
);
create table orders(
num int primary key auto_increment,
orderdate char(15) not null,
customerid char(10),
amount int not null
);
insert into customers
values
('A123', 'Alice', 'aceee@email.com'),
('j_mes_id', 'James', 'j_mes@email.com'),
('popo', 'Pauline', 'pol2@email.com');
insert into orders
(orderdate, customerid, amount)
values
('21-10-25', 'j_mes_id', 56000),
('21-11-17', 'popo', 73200),
('21-11-27', 'j_mes_id', 34900);
JOIN : ν μ΄λΈμ κ²°ν©
CROSS JOIN
-
ν μͺ½ ν μ΄λΈμ λͺ¨λ νλ€κ³Ό λ€λ₯Έ ν μ΄λΈμ λͺ¨λ νμ μ‘°μΈμν€λ κΈ°λ₯
-
SELECT * FROM table_name1, table_name2;
-
ex)
SELECT * FROM customers, orders;
INNER JOIN
-
κΈ°μ€ ν μ΄λΈκ³Ό μ‘°μΈ ν μ΄λΈ λͺ¨λμ λ°μ΄ν°κ° μ‘΄μ¬ν΄μΌ μ‘°νλ¨
-
IMPLICIT INNER JOIN
-
SELECT * FROM table_name1, table_name2 WHERE table_name1.column_name = table_name2.column_name;
-
ex)
select * from customers, orders where customers.customerid = orders.customerid order by num;
-
-
EXPLICIT INNER JOIN
-
SELECT * FROM table_name1 JOIN table_name2 ON table_name1.column_name = table_name2.column_name;
-
ex)
select * from customers join orders on customers.customerid = orders.customerid;
-
LEFT JOIN
-
ν μ΄λΈ1 μ 체 + ν μ΄λΈ1, ν μ΄λΈ2μ ν©μ§ν©
-
μΌμΉνλ κ°μ΄ μλλΌλ μΌμͺ½ κ°(ν μ΄λΈ1μ κ°) λͺ¨λ μ‘°ν, λ°μ΄ν°κ° μμΌλ©΄ NULL
-
SELECT * FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name = table_name2.column_name;
-
ex)
SELECT * FROM customers LEFT JOIN orders ON customers.customerid = orders.customerid order by num;
RIGHT JOIN
-
ν μ΄λΈ1, ν μ΄λΈ2μ ν©μ§ν© + ν μ΄λΈ2 μ 체
-
μΌμΉνλ κ°μ΄ μλλΌλ μ€λ₯Έμͺ½ κ°(ν μ΄λΈ2μ κ°) λͺ¨λ μ‘°ν, λ°μ΄ν°κ° μμΌλ©΄ NULL
-
SELECT * FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name = table_name2.column_name;
-
ex)
insert into orders (orderdate, customerid, amount) values ('21-11-28', 'mylll', 46300); SELECT * FROM customers RIGHT JOIN orders ON customers.customerid = orders.customerid order by num;
UNION
-
JOIN : κ°λ‘ κ²°ν© λ°©μ / UNION : μΈλ‘ κ²°ν© λ°©μ
-
SELECT column_name1 FROM table_name1 UNION (ALL) SELECT column_name2 FROM table_name2
-
λ κ° ν μ΄λΈμ μ‘°νν μ»¬λΌ κ°μλ μΌμΉν΄μΌ ν¨
-
UNION ALL : μ€λ³΅λ λ°μ΄ν° λͺ¨λ νμ
-
-
ex)
create table schoolA( name char(10), subject char(10), score int ); insert into schoolA values ('μ΅κ°', 'κ΅μ΄', 86), ('κ°μλ²½', 'μμ΄', 78); create table schoolB( stuName char(10), stuSubject char(10), stuScore int ); insert into schoolB values ('κ°μλ²½', 'μμ΄', 78), ('λ°νλ', 'μμ΄', 89), ('μ΄λ°λ€', 'μν', 100); # union select name, score from schoolA union select stuName, stuScore from schoolB; # union all select name, score from schoolA union all select stuName, stuScore from schoolB;