
๋ ์ง : 2021๋ 11์ 7์ผ
์์ฒญ ๊ฐ์ ; SQL CH02
SQL ๊ณต๋ถ๋ฅผ ํด์ผํด์ ์ค๋์ ์๊ณ ๋ฆฌ์ฆ ๊ฐ์๊ฐ ์๋๋ผ SQL ๊ฐ์๋ฅผ ๋ค์๋ค.
๊ธฐ๋ณธ์ ์ธ ๊ธฐ๋ฅ๋ค์ ์๋ ค์ฃผ์ จ๋๋ฐ, ๋๋ MySQL์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์, https://www.mysqltutorial.org/ ๋ฅผ ์ฐธ๊ณ ํ์ฌ ์ ๋ฆฌํด ๋ณด์๋ค.
<1> Querying Data
- Use the
SELECTstatement to select data from a table.
- Use the
SELECT *to select data from all columns of a table.
SELECT:
- MySQL
SELECTstatement doesn’t require theFROMclause
- Use the
dualtable if you want to use theFROMclause but don’t want to reference a table. (dual์ dummy table์)
- Assign an alias to a column to make it more readable.
1. Select
In MySQL, SELECT statement is used to query data from the table.
SELECT select_list #case not sensitive
FROM table_name;
Example
Retrieve Data from single Column
select lastName;
from employees;
Receive Data from multiple Columns
select lastName,
firstName,
jobTitle
from employees;
Retrive all
select * from employee;s
2. Creating Table
Create
In MySQL, you can create using
CREATEkeyword
create table members(
member_id int auto_increment,
name varchar(100),
primary key (member_id)
);
Insert
In MySQL, you can insert data using
INSERT INTOkeyword
insert into members(name) -- ๋ค๋์ name ์ถ๊ฐ
values('John'),('Jane'),('David');
<2> Sorting Data
- Use the
ORDER BYclause to sort the result set by one or more columns.
- Use the
ASCoption to sort the result set in ascending order and theDESCoption to sort the result set in descending order.
- The
ORDER BYclause is evaluated after theFROMandSELECTclauses.
- In MySQL,
NULLis lower than non-NULL values
1. Order By
When using
SELECTstatement, the order of rows in the result set is unspecified. In order to sort the dataset, use
ORDER BYclause.
select select_list
from table_name
order by
column1 [ASC|DESC],
column2 [ASC|DESC],
...;
Ascending
Ascending order → ๋ช ์ํ์ง ์์ผ๋ฉด ๊ธฐ๋ณธ์ ์ผ๋ก ASC์ด๋ค
Descending
ORDER BY column1 DESC;
Sort Result set by one column
select first_name,
last_name,
from employees
order by last_name;
Sorting multiple columns
select first_name,
last_name,
hire_date
from employees
order by
last_name ASC
hire_date DESC;
Sorting result set
You can also sort result expression using
order byclause
select first_name,
last_name,
salary*commision_pct AS '๋๋'
from employees
order by
salary*commission_pct DESC;
2. Field () Function
FIELD(str1, str2, ....) -- syntax
Field() function returns position of the string in the str1, str2, ... list.
Example:
SELECT FIELD ('B','A','B','C');
SELECT FEILD('D','A','B','C');
Sort data using a custom list
EXAMPLE 1:
Suppose that you want to sort the sales orders based on their statuses in the following order:
- In Process
- On Hold
- Canceled
- Resolved
- Disputed
- Shipped
SELECT
orderNumber, status
FROM
orders
ORDER BY FIELD(status,
'In Process',
'On Hold',
'Cancelled',
'Resolved',
'Disputed',
'Shipped');
๋ฆฌ์คํธ: status๋ฅผ order ํด๋ผ. ์ด๋ ์์ผ๋ก? ๋ฌธ์ ์์ ์ฃผ์ด์ง ์์ผ๋ก
EXAMPLE2 :
Employees ์์ Salary๋ฅผ job_id, hire_date ์์ผ๋ก order ํด๋ผ
select first_name, -- ํ
์ด๋ธ column์ ๋ณด์ผ ๋ด์ฉ
last_name,
job_id,
hire_date,
salary
from employees -- from which table?
order by field( -- order salary:
salary,
job_id, -- by 1. job_id
hire_date -- and 2. hire_date
);
Order by and Null
In mySQL, NULL comes before non-null values.
- Order By [ASC] : null comes on top
- Order By [DESC] : null comes last
<3> Filtering Data
1. Where
Specify a search condition for the row returned by query
SELECT select_list
FROM table_name
WHERE search_condition;
Equality Operator
SELECT last_name,
first_name,
job_id
FROM employees
WHERE job_id='IT_PROG';
JOB ID๊ฐ IT PROG์ธ ์ง์๋ค์ ์ ํ
AND Operator
job_id๊ฐ IT PROG ์ด๊ณ (AND), ์ฐ๋ด์ด 5000 ์ด์์ธ ์ง์
SELECT last_name,
first_name,
job_id,
salary
FROM employees
WHERE job_id='IT_PROG'
AND salary>5000;
OR Operator
job_id๊ฐ IT PROG ์ด๊ฑฐ๋(OR) FI ACCOUNT ์ด๊ณ (AND), ์ฐ๋ด์ด 5000 ์ด์์ธ ์ง์
SELECT last_name,
first_name,
job_id,
salary
FROM employees
WHERE (job_id='IT_PROG'
OR
job_id='FI_ACCOUNT')
AND salary >5000;
BETWEEN Operator
Between Operator returns true if a value is in a range
expression BETWEEN A and B -- syntax
employee id ๊ฐ 100-110 ์ธ ์ง์๋ค
SELECT employee_id,
first_name,
last_name
FROM employees
WHERE employee_id BETWEEN 100 AND 110
ORDER BY employee_id;
LIKE Operator
LIKE Operator evalutaes to TRUE if a value matches a specified pattern → Pattern์ % ์ _ ์์ผ๋ ์นด๋๋ก ์ ์๋๋ค.
- % : matches any string of zero or more characters (ํฌํจ)
- _ : matches any single character (๋ฒ์งธ)
%Son : ์ฑ์ด son์ผ๋ก ๋๋๋ ์ด๋ฆ
SELECT
first_name,
last_name
FROM
employees
WHERE
last_name LIKE '%son'
ORDER BY first_name;
%se% :์ฑ์ se๋ฅผ ๋ฌธ์์ด๋ก ํฌํจํ๋ ์ด๋ฆ
SELECT
first_name,
last_name
FROM
employees
WHERE
last_name LIKE '%se%'
ORDER BY first_name;
%s_ : ์ฑ์ ๋์์ ๋๋ฒ์งธ ๊ธ์๊ฐ s์ธ ์ด๋ฆ
SELECT
first_name,
last_name
FROM
employees
WHERE
last_name LIKE '%s_'
ORDER BY first_name;
IN Operator
IN Operator returns true if a value matches any value in a list
value IN (val1, val2...) -- syntax
๋ถ์ ๋ฒํธ๊ฐ 10,90,100์ธ ์ง์์ ๊ณ ๋ฅด์์ค.
SELECT
first_name,
last_name,
department_id
FROM
employees
WHERE
department_id IN (60,90,100)
ORDER BY
department_id;
The following table shows the comparison operators that you can use to form the expression in the WHERE clause.
WHERE ์ ์ Operators
| Operator | Description |
|---|---|
| = | Equal to. You can use it with almost any data type. |
| <> or != | Not equal to |
| < | Less than. You typically use it with numeric and date/time data types. |
| > | Greater than. |
| <= | Less than or equal to |
| >= | Greater than or equal to |
NOT EQUAL Operator(<>)
<> : ~ ๊ฐ ์๋
SELECT
last_name,
first_name,
job_id
FROM
employees
WHERE
job_id <> 'IT_PROG';
2. DISTINCT
SELECT DISTINCT ์ → remove duplicate rows
#SYNTAX
SELECT DISTINCT select_list
FROM table_name
WHERE search_condition
ORDER BY sort_expression;
One column
WIthout Distinct vs With Disctinct → ์ค๋ณต๋ lastname ์ด ์ ๊ฑฐ๋๋ค
SELECT
last_name
FROM
employees
ORDER BY
last_name;
^ DISTINCT๊ฐ ์์ฐ์: Grant ๋ ์ฑ์ด ์ค๋ณต๋ ๋งํผ ํ ์ด๋ธ์ ๋ณด์ฌ์ค๋ค
SELECT
DISTINCT last_name
FROM
employees
ORDER BY
last_name;
^ When Distinct is used: Grant only appears once on the table
NULL Values
When you specify a column with
NULL valuesin the Distinct Clause → it
only keeps one null values๐ You can also do this:
WHERE State IS NOT NULL
Using Not Null with where condition gives same result with saying, select distinc state
Where์ ์ํ๋ฌธ์ด ๋ ๋จผ์ ๊ธฐ ๋๋ฌธ์, ์ฝ๋๋ฅผ ์งค ๋ ์ด๋๊ฒ ๋ ํจ์จ์ ์ธ์ง๋ฅผ ์๊ฐํ๋ฉฐ ์ง์ผํ๋ค.
Multiple Column
You can use multiple columns in the distinct clause, and it will use combination of values in theses columns → So yes, if both column and row contents are same it will omit one but else if theres multiple on columns & each rows are unique → it will still display multiples columns but with unique rows
SELECT DISTINCT job_id, first_name,last_name
FROM employees
ORDER BY last_name;
Yes, there are multiple SA_REP → but Ellen and Sundar are distinct
And Yes, there are two Cambrault but the are different person
→ In mySQL, when you use distinct on multiple columns it use combination of values so they are all at the end, unique
3. AND OPERATOR
WHERE ์ ์์๋ ๋ค๋ฃจ์์ง๋ง, AND OPERATOR can be combined into multiple boolean expressions to filter data. AND returns 0,1, or NULL
A AND B --syntax
MySQL์์ Null ์ด๋: ์ ์ ์๋ ์๋ฅผ ๋ปํ๋ค.
๋ฐ๋ผ์, true & null ์ ์ ์ ์์ง๋ง, false & null ์ false ๊ฐ ๋๋ ๊ฒ์ด๋ค
Short-Circuit Evaluation:
SELECT 1 = 0 AND 1 / 0; -- and ์ฐ์ฐ์ short circuit evaluation
SELECT 1 = 2 OR 1 / 0; -- or ์ฐ์ฐ์ short circuit evaluation
4. OR OPERATOR
A OR B --syntax
์์ AND์์ ์ค๋ช ํ๋๊ฒ๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก, MySQL์์ NULL์ ์ ์ ์๋ ์์ด๋ค. ๋ฐ๋ผ์, OR ์ฐ์ฐ์์ ์์์๋์ or true๋ ํ๋๋ผ๋ true์ด๋ฏ๋ก true, ์์์๋์ or false๋ ์์์๋์์ ๊ฐ์ ๋ชจ๋ฅด๊ธฐ๋๋ฌธ์ ์์ ์๋ ์ ์ฆ null์ returnํ๋ค
5. IN Operator
IN Operator allows you to determine if a value matches any value in a list of values
→ value=value1 OR value =value2 OR value=value3 OR...์ ๋ฌถ์๊ฒ์ด๋ผ๊ณ ๋ณด๋ฉด ๋๋ค → value in (value1,value2,value3...)
WHERE ์ ์ด๋ SELECT์ ์์ ์ฃผ๋ก ์ฐ์ธ๋ค
SELECT
officeCode,
city,
phone
FROM
offices
WHERE
country = 'USA' OR country = 'France';
SELECT
officeCode,
city,
phone
FROM
offices
WHERE
country IN ('USA', 'France');
์์ ๋ ์ฝ๋๋ ๊ฐ์ ์ฝ๋์ด๋ค
6. NOT IN Operator
value NOT IN (value1, value2, value3 ...) -- syntax
value <> value1 AND value<> value2 <> value<> value3 -- Use <>
NOT(value= value1 OR value =value2 OR value=value3.....) --USE NOT OR
NOT IN ์ ์ฐ๋ฉด ์ฝ๊ฒ ๋ฌถ์ ์ ์๋ค. <>์ ํ๋์ผ๋๋ง ์ฐ์..
7. BETWEEN
value BETWEEN val1 AND val2; --BETWEEN A AND B
value >= val1 AND value<=val2
value NOT BETWEEN val1 AND val2 --NOT BETWEEN A AND B
value <val2 OR value>val1
๋ง์ผ, ๋ ์ง๊ฐ range ์์ ๋๋์ง ๋ณด๊ณ ์ถ์ ๋:
SELECT
orderNumber,
requiredDate,
status
FROM
orders
WHERE
requireddate BETWEEN
CAST('2003-01-01' AS DATE) AND
CAST('2003-01-31' AS DATE);
→used CAST() to cast the literal string '2003-01-01' into a DATE value:
8. LIKE
- Use the
LIKEoperator to test if a value matches a pattern.
- The
%wildcard matches zero or more characters.
- The
_wildcard matches a single character.
- Use
ESCAPEclause specifies an escape character other than the default escape character (\).
- Use the
NOToperator to negate theLIKEoperator.
LIKE๋ ํจํด์ ์ฐพ์ ๋ ์ฐ์ธ๋ค
% Wilde Card
- 'A%' : A ์ผ๋ก ์์
SELECT
employeeNumber,
lastName,
firstName
FROM
employees
WHERE
firstName LIKE 'a%'; -- Firstname์ด a ๋ก ์์ํ๋ ์ฌ๋ (๋์๋ฌธ์ x)
- '%A' : A ์ผ๋ก ๋๋จ
SELECT
employeeNumber,
lastName,
firstName
FROM
employees
WHERE
firstName LIKE '%son'; -- Firstname์ด son ๋ก ๋๋๋ ์ฌ๋
- '%A%' : A๊ฐ ๋ฌธ์์ด ์ค๊ฐ์ ํฌํจ๋จ
SELECT
employeeNumber,
lastName,
firstName
FROM
employees
WHERE
firstName LIKE '%so%'; -- Firstname์ so ๊ฐ ๋ค์ด๊ฐ๋ ์ฌ๋
_ Wild Card
- 'A_B' : AaB, AbB, AcB,AdB.... ๋ฑ ์ค๊ฐ์ ๋ค์ด๊ฐ๋๊ฑด ์๊ด ์์
SELECT
employeeNumber,
lastName,
firstName
FROM
employees
WHERE
firstName LIKE 't_m'; -- tom, tim ๋ฑ firstname์ t_m์ธ ๋ฌธ์์ด
NOT
NOT Operator์ ์ฐ๋ฉด, ์ด๋ฅผ ์ ์ธํ ๋ชจ๋ ๋ฌธ์์ด์ด ๋์ด
ESCAPE
Pattern ์ด %๋ _ ๋ฑ์ ์บ๋ฆญํฐ๋ฅผ ํฌํจํ๊ณ ์์ ๋, escape์ ์ ์ด๋ค
→ ๋ฐฑ๋ถ์จ %๋ผ๋ฉด : %_20%๋ผ๊ณ ํ๋ค๋ฉด 20์ ํฌํจํ๋ ๋ฌธ์์ด์ ์ฐพ๊ฒ๋๋ค. ์ด๋ backslash๋ฅผ ์ฌ์ฉํ์ฌ %\_20%๋ผ๊ณ ํํํ๋ฉด ์ ์์ ์ผ๋ก ์๋ํ๋ค
%์ _ ๋ฟ๋ง์๋๋ผ $๊ฐ์ SPECIAL CHARACTERES๋ ํฌํจํ๋ค
SELECT
productCode,
productName
FROM
products
WHERE
productCode LIKE '%$_20%' ESCAPE '$';
9. LIMIT
use LIMIT to constrain the number of rows returned by SELECT statement
# SYNTAX
SELECT select_list
FROM table_name
LIMIT [offset,] row_count;
-- offset: specifies the offset of the first row to return (0๋ถํฐ ์์)
-- row_count: specifies the maximum number of rows to return
Example:
Get Highest / Lowest rows
SELECT
employee_id,
start_date,
end_date
FROM job_history
ORDER BY (end_date - start_date) DESC
LIMIT 5;
์ผ ๊ฒฝ๋ ฅ์ด ๊ฐ์ฅ ํฐ ์ฌ๋ top (highest) 5๋ช ์ ์ฐ์ถ
Pagination
When you display data on the screen, you foten want to divide rows into pages, where each page contains a limited number of rows liek 10 or 20
You can use LIMIT to do so:
- Use COUNT(*) aggregate function to get the total rows
SELECT COUNT(*)
FROM employees;
- Use LIMIT to get rows of page 1 which contains frist alphabetically sorted 10 employees
SELECT first_name,
last_name
FROM employees
ORDER BY last_name
LIMIT 10;
3. Use LIMIT to get second page →11~20:
SELECT first_name,
last_name
FROM employees
ORDER BY last_name
LIMIT 10 ,10;
GET Nth Highest or Lowest Value
- Nth : LIMIT n-1,1 returns 1 row starting at the row nn-1์ธ ์ด์ : index๊ฐ 0๋ถํฐ ์์ํ๋ค
# SYNTAX
SELECT select_list
FROM table_name
ORDER BY sort_expression
LIMIT n-1, 1;
Find employee with second-highest work experience:
n: 2๋ฒ์งธ → n-1 =1
SELECT
employee_id,
start_date,
end_date
FROM job_history
ORDER BY (end_date - start_date) DESC
LIMIT 1,1;
Find top 3 employees with highest work experience:
SELECT
employee_id,
start_date,
end_date
FROM job_history
ORDER BY (end_date - start_date) DESC
LIMIT 0,3;
→ ํ์ง๋ง, ์ด๋ฐ ๊ฒฝ์ฐ์๋ LIMIT3; ๊ณผ ๋์ผํ function์
LIMIT & DISTINCT clauses
If you use LIMIT clause with the DISTINCT clause → MySQL immediately stops seraching when it finds the number of unique rows specified in the LIMIT clause
-- Syntax:
SELECT DISTINCT row_name
FROM table_name
WHERE row_name is something
LIMIT limit_number;
Example:
SELECT DISTINCT
state
FROM
customers
WHERE
state IS NOT NULL
LIMIT 5;
10. IS NULL
- Use the
IS NULLoperator to test if a value isNULLor not. TheIS NULLoperator returns one if a value isNULL.
- The
IS NOT NULLreturns one if a value is notNULL
Test whether a value is NULL or not by using IS NULL operator
MySQL์์์ null ์ ์ ์ ์๋ ๊ฐ์ด๋ค. → false ๊ฐ ์๋๋ ํผ๋ x
value is null -- syntax
value is not null
SELECT 1 is null, -- 0
0 is null, -- 0
null is null -- 1(true)
To be Compatible with ODBC programs, MySQL supports some specialized features of the IS NULL operator → Date ('0000-00-00') and @@sql_auto_is_null variable
DATE
- If a DATE or DATETIME column has a NOT NULL constraint and contains a special date '0000-00-00', you can use the IS NULL operator to find such rows.
CREATE TABLE IF NOT EXISTS projects ( -- project ํ
์ด๋ธ ๋ง๋ค๊ธฐ
id INT AUTO_INCREMENT,
title VARCHAR(255),
begin_date DATE NOT NULL, -- date ์ not null function ์ฃผ๊ธฐ
complete_date DATE NOT NULL,
PRIMARY KEY(id)
);
- Insert some rows
INSERT INTO projects(title,begin_date, complete_date) -- ํ
์ด๋ธ์ ๊ฐ ์ถ๊ฐ
VALUES('New CRM','2020-01-01','0000-00-00'), -- 0000-00-00 : null date
('ERP Future','2020-01-01','0000-00-00'),
('VR','2020-01-01','2030-01-01');
- Use IS NULL operator to select rows with the values in the complete_date column is 0000-00-00
SELECT *
FROM projects
WHERE complete_date IS NULL; -- date๊ฐ null ์ธ ๋ฐ์ดํฐ๋ฅผ ์ฐพ๋๋ค: 0000-00-00์ธ ๋ ์ง
@@sql_auto_is_null
If the variable @@sql_auto_is_null is set to 1, you can
get the value of an auto_increment columnafter executing an INSERT statement by using the IS NULL operator.
- Set variable @@sql_auto_is_null to 1
SET @@sql_auto_is_null = 1;
- Insert new row into the project table:
INSERT INTO projects(title,begin_date, complete_date)
VALUES('MRP III','2010-01-01','2020-12-31');
- Use IS NULL operator to get the generated value of the id column
SELECT
id
FROM
projects
WHERE
id IS NULL;
<4> Joining Tables
1. Alias
Alias for Columns
# Syntax
-- 1:
SELECT
[column_1 | expression] AS descriptive_name
FROM table_name;
-- 2: As ์๋ต
SELECT
[column_1 | expression] AS descriptive_name
FROM table_name;
-- 3: `` ๋ '' ๋ก ๋ฌถ๊ธฐ
SELECT
[column_1 | expression] AS `descriptive_name`
FROM table_name;
Concat_WS()
SELECT
CONCAT_WS(',' ,last_name,first_name)
FROM employees;
CONCAT_WS () ๋ฅผ ์ฐ๊ณ ๋ ํ, table column์ ์ด๋ฆ์ ์ดํด๋ณด๋ฉด, SELECT ์์ ๊ตฌ์ ์ด ๊ทธ๋๋ก ๋ค์ด๊ฐ์๋๊ฒ์ ๋ณผ ์ ์๋ค → ๊ฐ๋ ์ฑ์ ๋ํด์ฃผ๊ธฐ ์ํด Alias ๋ฅผ ์ฌ์ฉํ๋ค
SELECT
CONCAT_WS(',' ,last_name,first_name) `FULL NAME`
FROM employees;
Alias for Table
Table ๋ช ๋ alias๋ฅผ ์ฌ์ฉํ์ฌ ๋ค๋ฅด๊ฒ ํ๊ธฐํ ์ ์๋ค
# Sytax:
table_name AS table_alias
# refer table column:
table_alias.column_name
[์์] employees์ e๋ผ๋ alias๋ฅผ ์ฃผ์๋ค
→ ํ์ฉ : table column์ ์ฝ๊ฒ refer ํ ์ ์๋ค
SELECT * FROM employees e;
SELECT
e.first_name,
e.last_name
FROM employees e
ORDER BY e.first_name;
WHY? Why do we use Table Alias???
Both Customers table and Orders table have customerNumbers. Thus, if we use without alias we will get an error : Error Code: 1052. Column 'customerNumber' in on clause is ambiguous
Thus, we need to use table alias
SELECT
customerName,
COUNT(o.orderNumber) total
FROM
customers c
INNER JOIN orders o ON c.customerNumber = o.customerNumber
GROUP BY
customerName
ORDER BY
total DESC;
2. Join
Introduction to MySQL Join clauses
A relational database consists of multiple related tables linking together using common columns, which are known as foreign key columns. Because of this, data in each table is incomplete from the business perspective.
On above database, to get complete order information → we need BOTH orders and orderDetails
→ That's when this "Join" Kicks in
MySQL supports :
Inner Join, Left Join, Right Join, and Cross Join
Let's create a sample table
-- Create Member and Committees Table
CREATE TABLE members (
member_id INT AUTO_INCREMENT,
name VARCHAR(100),
PRIMARY KEY (member_id)
);
CREATE TABLE committees (
committee_id INT AUTO_INCREMENT,
name VARCHAR(100),
PRIMARY KEY (committee_id)
);
-- Insert Name Data
INSERT INTO members(name)
VALUES('John'),('Jane'),('Mary'),('David'),('Amelia');
INSERT INTO committees(name)
VALUES('John'),('Mary'),('Amelia'),('Joe');
-- Query Data
SELECT * FROM members;
SELECT * FROM committees;
3. Inner Join
Inner Join clause joins two tables based on a condition which is known as a join predicate.
The inner join clause compares each row from the first table with every each row from the second table. If values from both row satisfy : inner join clause creates a new row whose column contains all the cloumns of two rows from both table. → Inner Join clause includes only matching rows from both tables
# Basic Syntax:
SELECT select_list
FROM t1 -- table ์ ํ
INNER JOIN t2 ON join_condition1 -- INNER JOIN A ON B
INNER JOIN t3 ON join_condition2
...;
๐
์ฆ, row ๊ฐ์ด ๊ฐ์ ์ ๋ค์ ํฉ์ณ์ ์ ํ ์ด๋ธ์ ๊ฐ์ ธ์จ๋คSELECT
m.member_id,
m.name AS member,
c.committee_id,
c.name AS committee
FROM
members m
INNER JOIN committees c ON c.name = m.name;
์ปจ๋์ ์ = ์ด์ฐ์ธ๋ค๋ฉด → USING() ์ฌ์ฉ
- inner join
- left join
- right join
- cross join
If the join condition uses equality operator(=) and column names in both tables used for matching are the same → use
USINGinstead
SELECT column_list
FROM table_1
INNER JOIN table_2 USING (column_name);
SELECT
m.member_id,
m.name AS member,
c.committee_id,
c.name AS committee
FROM
members m
INNER JOIN committees c USING(name);
SELECT
productCode,
productName,
textDescription
FROM
-- products t1
-- INNER JOIN productlines t2
-- ON t1.productline = t2.productline; -> = ๋ค์ด๊ฐ ์ ๋ค์ using ์ผ๋ก ๋์ฒด
products
INNER JOIN productLines USING (productline); --JOIN table using (varname)
JOIN Multiple tables
SELECT
orderNumber,
orderDate,
customerName,
orderLineNumber,
productName,
quantityOrdered,
priceEach
FROM
orders
INNER JOIN orderdetails
USING (orderNumber)
INNER JOIN products
USING (productCode)
INNER JOIN customers
USING (customerNumber)
ORDER BY
orderNumber,
orderLineNumber;
4. Left Join
Left join selects data strating from the left table. For each row in the left table, the left join compares with every row in the right table.
→ Left join selects all data from the left table whether there are matching row exists in the right table or not
SELECT column_list
FROM table_1
LEFT JOIN table_2 ON join_condition;
๐ ์ฆ, Left Join์ ์ผ์ชฝ ํ ์ด๋ธ์ ์ ์งํ ์ฑ๋ก ์ค๋ฅธ์ชฝ ํ ์ด๋ธ๊ณผ ๋น๊ต (์ค๋ฅธ์ชฝ์ ๊ฐ์ด ์์ผ๋ฉด null)
SELECT
m.member_id,
m.name AS member,
c.committee_id,
c.name AS committee
FROM
members m
LEFT JOIN committees c USING(name);
5. Right Join
The right join clause is similar to the left join clause except that the treatment of left and right tables is reversed. The right join starts selecting data from the right table instead of the left table.
# Syntax
SELECT column_list
FROM table_1
RIGHT JOIN table_2 ON join_condition;
๐ ์ฆ, Right Join์ ์ค๋ฅธ์ชฝ ํ ์ด๋ธ์ ์ ์งํ ์ฑ๋ก ์ผ์ชฝ ํ ์ด๋ธ๊ณผ ๋น๊ต (์ผ์ชฝ์ ๊ฐ์ด ์์ผ๋ฉด null)
Committee(์ค๋ฅธ์ชฝ ํ ์ด๋ธ)์ ์ ๋ถ ์กด์ฌ (๋น๊ต ๊ธฐ์ค)
SELECT
m.member_id,
m.name AS member,
c.committee_id,
c.name AS committee
FROM
members m
RIGHT JOIN committees c USING(name); -- ==> committees c on c.name = m.name
6. Cross Join
Unlike the inner join, left join, and right join, the cross join clause does not have a join condition.
The cross join makes a Cartesian product of rows from the joined tables. The cross join combines each row from the first table with every row from the right table to make the result set.
์ฒซ๋ฒ์งธ ํ ์ด๋ธ์ด n rows, ๋๋ฒ์งธ ํ ์ด๋ธ์ด m rows๊ฐ ์์๋ค๋ฉด, cross join์ ์ด nxm rows ๋ฅผ returnํ๋ค
# syntax
SELECT select_list
FROM table_1
CROSS JOIN table_2;
SELECT
m.member_id,
m.name AS member,
c.committee_id,
c.name AS committee
FROM
members m
CROSS JOIN committees c;
7. Self-join
There is a special case that you need to join a table to itself → The self join is often used to query hierarchical data or to compare a row with other rows within the same table.
SELF JOIN USING INNER JOIN
๊ฐ์ ํ ์ด๋ธ ๋ด์์, Manager๋น ๋ถํ ๋ฆฌ์คํธ ๋ฝ์๋ด๊ธฐ
SELECT
CONCAT(m.lastName, ', ', m.firstName) AS Manager,
CONCAT(e.lastName, ', ', e.firstName) AS 'Direct report'
FROM
employees e
INNER JOIN employees m ON
m.employeeNumber = e.reportsTo
ORDER BY
Manager;
Self Join using Left join
SELECT
INFULL(CONCAT(m.lastname,', ',m.first_name), 'Top Manager') AS 'Manager',
CONCAT(e.lastname,', ',e.first_name) AS 'Direct Report'
FROM employees e
LEFT JOIN employees m --์ผ์ชฝ์ ์์ ๊ธฐ์ค์ : managers
on m.employeeNumber = e.reportsto
ORDER BY mangager DESC;
Self join to compare successive rows
In this example, the table customers is joined to itself using the following join conditions:
c1.city = c2.citymakes sure that both customers have the same city.
c.customerName > c2.customerNameensures that no same customer is included.
SELECT
c1.city,
c1.customerName,
c2.customerName
FROM
customers c1
INNER JOIN customers c2 ON
c1.city = c2.city
AND c1.customername > c2.customerName
ORDER BY
c1.city;
<5> Grouping Data
1. Group By
# Syntax:
SELECT c1, c2,..., cn, aggregate_function(ci)
FROM table
WHERE where_conditions
GROUP BY c1 , c2,...,cn;
Simple Group By Example
SELECT status
FROM orders
GROUP BY status;
GROUP BY๋ฅผ ์ฐ์ง ์๊ณ , SELECT DISTINCT status ๋ฅผ ์จ๋ ์์ ๊ฐ์ ๊ฒฐ๊ณผ๊ฐ ๋์จ๋ค
Use Group by with aggregate functions
SELECT
status, COUNT(*)
FROM
orders
GROUP BY status;
์๋ก ๋ค๋ฅธ ๋ ํ ์ด๋ธ์์ status: order quantities ๊ฐ์ ธ์ค๊ธฐ
SELECT
status,
SUM(quantityOrdered * priceEach) AS amount --quantityOrdered๋ priceEach๋ ๋ค๋ฅธ ํ
์ด๋ธ์ ์๋ ๋ฐ์ดํฐ
FROM
orders --from: ํ์ฌ ํ
์ด๋ธ
INNER JOIN orderdetails --inner join : ๋ค๋ฅธ ํ
์ด๋ธ
USING (orderNumber) --using :ํ์ฌ ํ
์ด๋ธ๊ณผ์ ๊ณตํต ์์ -> order number
GROUP BY --group by: status๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฌถ์ ๊ฑฐ์ผ
status;
Using Group by with expression
SELECT
YEAR(orderDate) AS year,
SUM(quantityOrdered * priceEach) AS total
FROM
orders -- ํ์ฌ ํ
์ด๋ธ
INNER JOIN orderdetails -- inner join : ํ ํ
์ด๋ธ
USING (orderNumber) -- using: ๊ณตํต ๋ณ์
WHERE
status = 'Shipped'
GROUP BY
YEAR(orderDate);
Group by with Having clause
Having: select the total sales of the year after 200
SELECT
YEAR(orderDate) AS year,
SUM(quantityOrdered * priceEach) AS total
FROM
orders
INNER JOIN orderdetails
USING (orderNumber)
WHERE
status = 'Shipped'
GROUP BY
year
HAVING
year > 2003;
Group By v.s. Distinct
If you use the GROUP BY clause in the SELECT statement without using aggregate functions, the GROUP BY clause behaves like the DISTINCT clause.
- Group by Clause:
SELECT
state
FROM
customers
GROUP BY state;
- Distinct Clause:
SELECT DISTINCT
state
FROM
customers;
Only Difference is , GROUP BY: Sort, DISTINCT : x sort
2. Having
The HAVING clause is used in the SELECT statement to specify filter conditions for a group of rows or aggregates.
HAVING clause is often used with the GROUP BY clause to filter groups
based on a specified condition. If you omit the GROUP BY clause, the HAVING clause behaves like the WHERE clause.
SELECT
select_list
FROM
table_name
WHERE
search_condition
GROUP BY
group_by_expression
HAVING
group_condition;
์์ group by ์์ ์ฐ์ธ ์์ ์ฐธ๊ณ (Having year>2003)
3. Roll up
Generate multiple grouping sets considering a hierarchy between columns specified in the GROUP BY clause.
SELECT
select_list
FROM
table_name
GROUP BY
c1, c2, c3 WITH ROLLUP;
UNION ALL
If you want to generate two or more grouping sets together in one query, you may use the UNION ALL operator:
SELECT
productline,
SUM(orderValue) totalOrderValue
FROM
sales
GROUP BY
productline
UNION ALL
SELECT
NULL,
SUM(orderValue) totalOrderValue
FROM
sales;
Because the UNION ALL requires all queries to have the same number of columns, NULL is is added in the select list of the second query to fulfill this requirement.
The NULL in the productLine column identifies the grand total super-aggregate line.
This query is able to generate the total order values by product lines and also the grand total row. However, it has two problems:
- The query is quite lengthy.
- The performance of the query may not be good since the database engine has to internally execute two separate queries and combine the result sets into one.
To fix these issues, you can use the ROLLUP clause.
The ROLLUP clause is an extension of the GROUP BY clause with the following syntax:
→ Fixed Code
SELECT
productLine,
SUM(orderValue) totalOrderValue
FROM
sales
GROUP BY
productline WITH ROLLUP;
SELECT
productLine,
orderYear,
SUM(orderValue) totalOrderValue
FROM
sales
GROUP BY
productline,
orderYear
WITH ROLLUP;
→ GROUP BY ์ ์กฐ๊ฑด์ ์ถ๊ฐํด์ฃผ๋ฉด order year ๋ณ๋ก productline์ ํฉ๊ณ๋ฅผ ๋ณด์ฌ์ฃผ๊ฒ ๋๋ค
Grouping() Function
To check whether NULL in the result set represents the subtotals or grand totals, you use the GROUPING() function → returns 1 when NULL occurs in a supper-aggregate row, otherwise, it returns 0.
SELECT
IF(GROUPING(orderYear),
'All Years',
orderYear) orderYear,
IF(GROUPING(productLine),
'All Product Lines',
productLine) productLine,
SUM(orderValue) totalOrderValue
FROM
sales
GROUP BY
orderYear ,
productline
WITH ROLLUP;
<6> Sub Queries
1. Subquery
Subquery is a query nested within another query such as SELECT, INSERT, UPDATE or DELETE. Also, a subquery can be nested within another subquery.
→ day3 ์์ ๋, where ์์ ์ง์ด๋ฃ์๊ฒ subquery์ผ
Subquery in Where clause
You can use comparison operators e.g., =, >, < to compare a single value returned by the subquery with the expression in the WHERE clause.
Scott์ ์ง๋ฌด์ ๊ฐ์ ์ฌ๋์ ์ด๋ฆ, ๋ถ์๋ช , ๊ธ์ฌ, ์ง๋ฌด๋ฅผ ๊ฒ์ํ์์ค
select
e.ename ์ด๋ฆ, -- ์๊ตฌํ๋ columns
d.dname ๋ถ์๋ช
,
e.sal ๊ธ์ฌ,
e.job ์ง๋ฌด
from emp e -- ๊ธฐ์ค์ด ๋๋ ํ
์ด๋ธ
inner join dept d using(deptno) -- table 2 using(๊ณตํตvar)
#subquery : e.job ์ด ์ด๋ฆ์ด scott์ธ ์ฌ๋์ job๊ณผ ์ผ์นํด์ผํ๋ค
where e.job = (
select job
from emp
where ename='scott'
);
์ ์ฒด ์ฌ์์ ํ๊ท ๊ธ์ฌ๋ณด๋ค ๊ธ์ฌ๊ฐ ๋ง์ ์ฌ์์ ์ฌ์๋ฒํธ, ์ด๋ฆ, ๋ถ์๋ช , ์ ์ฌ์ผ, ์ง์ญ, ๊ธ์ฌ๋ฅผ ๊ฒ์ํ์์ค
select
e.empno ์ฌ์๋ฒํธ,
e.ename ์ด๋ฆ, -- ์๊ตฌํ๋ columns
d.dname ๋ถ์๋ช
,
e.hiredate ์
์ฌ์ผ,
d.loc ์ง์ญ,
e.sal ๊ธ์ฌ
from emp e -- ๊ธฐ์ค์ด ๋๋ ํ
์ด๋ธ
inner join dept d using(deptno) -- table 2 using(๊ณตํตvar)
#subquery
where e.sal > ( -- ์กฐ๊ฑด: e.sal > avg(Sal)
select avg(sal) -- ํ๊ท ๊ธ์ฌ
from emp -- from which table?
);
Subquery with IN and NOT IN operators
If a subquery returns more than one value, you can use other operators such as IN or NOT IN operator in the WHERE clause.
- in
'King'์ด๋ 'James'์ ๊ธ์ฌ์ ๊ฐ์ ์ฌ๋์ ์ฌ์๋ฒํธ, ์ด๋ฆ,๊ธ์ฌ๋ฅผ ๊ฒ์ํ์์ค
select
e.empno ์ฌ์๋ฒํธ,
e.ename ์ด๋ฆ,
e.sal ๊ธ์ฌ
from emp e
where e.sal in ( -- ์ด๊ฒ๋ in์ด๋ค..
select sal
from emp
where ename in ('king','james')
);
- not in
10 ๋ฒ ๋ถ์ ์ค์์ 30๋ฒ ๋ถ์์๋ ์๋ ์๋ฌด๋ฅผ ํ๋ ์ฌ์์ ์ฌ์๋ฒํธ, ์ด๋ฆ, ๋ถ์๋ช , ์ ์ฌ์ผ, ์ง์ญ์ ๊ฒ์ํ์์ค
select
e.empno ์ฌ์๋ฒํธ,
e.ename ์ด๋ฆ, -- ์๊ตฌํ๋ columns
d.dname ๋ถ์๋ช
,
e.hiredate ์
์ฌ์ผ,
d.loc ์ง์ญ
from emp e
inner join dept d using(deptno)
where e.deptno = 10 -- dept no ๊ฐ 10์ด๊ณ
and
e.job not in -- e.job์ด 30๋ฒ ๋ถ์์๋ ์๋ค
(
select job
from emp
where deptno=30
);
Subquery in the from clause
When you use a subquery in the FROM clause, the result set returned from a subquery is used as a temporary table. This table is referred to as a derived table or materialized subquery.
SELECT
MAX(items),
MIN(items),
FLOOR(AVG(items))
FROM
(SELECT orderNumber, COUNT(orderNumber) AS items
FROM orderdetails
GROUP BY orderNumber) AS lineitems;-- lineitems๋ derived table ์ด๋ค(์๋์ฐธ๊ณ )
Subquery in Exists and Not Exists
When a subquery is used with the EXISTS or NOT EXISTS operator, a subquery returns a Boolean value of TRUE or FALSE.
SELECT *
FROM table_name
WHERE EXISTS( subquery );
2. Derived Table
The term derived table and subquery is often used interchangeably.When a stand-alone subquery is used in the FROM clause of a SELECT statement, it is also called a derived table.
# Syntax
SELECT select_list
FROM (
SELECT select_list
FROM table_1
) derived_table_name
WHERE derived_table_name.c1 > 0;
3. Exists
The EXISTS operator is a Boolean operator that returns either true or false. The EXISTS operator is often used to test for the existence of rows returned by the subquery.
# Syntax
SELECT select_list
FROM a_table
WHERE [NOT] EXISTS(subquery);
Exists VS In Operator
The query that uses the
EXISTS operator is much fasterthan the one that uses the IN operator.
<7> Common Table Expressions
What is Common Table Expression(CTE)
A common table expression is a named temporary result set that exists only within the execution scope of a single SQL statement e.g.,SELECT, INSERT, UPDATE, or DELETE.
โ๏ธ Derived Table๊ณผ ๊ณตํต์ : not stored as an object and last only during the execution of a query
โ๏ธ Derived Table๊ณผ ์ฐจ์ด์ : CTE can be self-referencing (a recursive CTE) or can be referenced multiple times in the same query. In addition, a CTE provides better readability and performance in comparison with a derived table.
Syntax
WITH cte_name (column_list) AS (
query
)
SELECT * FROM cte_name;
Example
WITH customers_in_usa AS (-- cte:customers in usa
SELECT -- query
customerName, state
FROM
customers
WHERE
country = 'USA'
) SELECT -- select something
customerName -- from cte table
FROM
customers_in_usa
WHERE
state = 'CA'
ORDER BY customerName;
With clause
There are some contexts that you can use the WITH clause to make common table expressions:
WITHclause can be used at the beginning ofSELECT,UPDATE, andDELETEstatements:
WITH ... SELECT ...
WITH ... UPDATE ...
WITH ... DELETE ...
WITHclause can be used at the beginning of a subquery or a derived table subquery:
SELECT ... WHERE id IN (WITH ... SELECT ...);
SELECT * FROM (WITH ... SELECT ...) AS derived_table;
- Third, a
WITHclause can be used immediately precedingSELECTof the statements that include aSELECTclause
CREATE TABLE ... WITH ... SELECT ...
CREATE VIEW ... WITH ... SELECT ...
INSERT ... WITH ... SELECT ...
REPLACE ... WITH ... SELECT ...
DECLARE CURSOR ... WITH ... SELECT ...
EXPLAIN ... WITH ... SELECT ...
<8>Set Operators
Set operators- Union, Union all, Intersect, and Minus operators
1. Union and Union All
UNION operator: combine two or more result sets from multiple SELECT statements into a single result set. ์ฆ, ๊ต์งํฉ์ ๊ตฌํด์ ํฉ์น๋ ๊ฒ
Union Operator
Combine two or more result sets of queries into a single result set
๐ ๊ท์น
- First, the number and the orders of columns that appear in all
SELECTstatements must be the same.→ ์์์ column #๊ฐ ๊ฐ์์ผ๋ง union์ ์ธ ์ ์์ด์, ๋ค๋ฅด๋ฉด null์ถ๊ฐํด์ค์ผํจ !
- Second, the data types of columns must be the same or compatible.
# Syntax:
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
...
Union operator์ DISTINCT ์์ด๋ ์ค๋ณต๋๋ rows๋ฅผ ์๋์ผ๋ก ์ ๊ฑฐํ๋ค
DROP TABLE IF EXISTS t1;
DROP TABLE IF EXISTS t2;
CREATE TABLE t1 (
id INT PRIMARY KEY
);
CREATE TABLE t2 (
id INT PRIMARY KEY
);
INSERT INTO t1 VALUES (1),(2),(3);
INSERT INTO t2 VALUES (2),(3),(4); --2 ๊ฐ ์ค๋ณต๋๋ค
#--------------------------------Union--------------------------------#
SELECT id
FROM t1
UNION
SELECT id
FROM t2;
#---------------------------------Result---------------------------------#
+----+
| id |
+----+
| 1 |
| 2 | --> 2๋ ํ๋ฒ๋ง ๋ค์ด๊ฐ๋ค
| 3 |
| 4 |
Union VS Join
- Join Combines result sets horizontally
- Union Combines result sets vertically
Alias
Example:
→ Employees ์ Customer์ ์ด๋ฆ ๋ช ๋จ ํฉ์น๊ธฐ(union)
SELECT
firstName,
lastName
FROM employees
Union
SELECT
contactFirstName,
contactLastName
FROM
Customers
→Concat์ ์ด์ฉํด์ ํ ์ด๋ธ ํฉ์น๊ธฐ
SELECT
CONCAT(firstName,' ',lastName) fullname
FROM
employees
UNION SELECT
CONCAT(contactFirstName,' ',contactLastName)
FROM
customers;
Order By
Union์ result set์ ์ ๋ ฌํ๊ณ ์ถ์ผ๋ฉด, SELECT์ ์ ๋ง์ง๋ง ๋ถ๋ถ์ ์ถ๊ฐํ๋ค
→ ๋ง์ผ Order By๋ฅผ ๋ง์ง๋ง ๋ถ๋ถ์ ์ถ๊ฐํ์ง ์์ผ๋ฉด ์ ๋ ฌ์ด ์ ๋๋ก ๋์ง ์๋๋ค !
SELECT
concat(firstName,' ',lastName) fullname
FROM
employees
UNION SELECT
concat(contactFirstName,' ',contactLastName)
FROM
customers
ORDER BY fullname;
ํ์ column์ ์ถ๊ฐํ์ฌ, employee์ธ์ง customer์ธ์ง ํ์
SELECT
CONCAT(firstName, ' ', lastName) fullname,
'Employee' as contactType
FROM
employees
UNION SELECT
CONCAT(contactFirstName, ' ', contactLastName),
'Customer' as contactType
FROM
customers
ORDER BY
fullname
2. Intersect
MySQL does not support the INTERSECT operator
MySQL์ intersect operator๋ฅผ ์ง์ํ์ง ์์ง๋ง, join์ ์ ์ฌ์ฉํ์ฌ ๋น์ทํ ํจ๊ณผ๋ฅผ ๋ผ ์์๋ค
๊ท์น
- The order and the number of columns in the select list of the queries must be the same.
- The data types of the corresponding columns must be compatible.
(SELECT column_list
FROM table_1)
INTERSECT
(SELECT column_list
FROM table_2);
Emulating INTERSECT in MySQL
MySQL does not support intersect operator, but you can emulate it
Set up Tables
CREATE TABLE t1 (
id INT PRIMARY KEY
);
CREATE TABLE t2 LIKE t1;
INSERT INTO t1(id) VALUES(1),(2),(3);
INSERT INTO t2(id) VALUES(2),(3),(4);
SELECT id FROM t1;-- get query from t1
SELECT id FROM t2;-- get query from t2
- Emulate Intersect using DISTINCT and INNER JOIN
SELECT DISTINCT -- ์ค๋ณต ์ ๊ฑฐ
id
FROM t1
INNER JOIN t2 USING(id); -- ํ
์ด๋ธ ํฉ์ฒด
- Emulate Intersect using IN and Subquery
SELECT DISTINCT id -- ์ฆ๋ฒ
์ ๊ฑฐ
FROM t1
WHERE id IN (SELECT id FROM t2); -- range: t1 ~ t2์์ ๋ชจ๋ ๋ด์ฉ์์
3. Minus
MySQL does not support the MINUS operator
Minus operator
The MINUS compares the results of two queries and returns distinct rows from the result set of the first query that does not appear in the result set of the second query.
๊ท์น
- The number and order of columns in both
select_list1andselect_list2must be the same.
- The data types of the corresponding columns in both queries must be compatible.
SELECT select_list1
FROM table_name1
MINUS
SELECT select_list2
FROM table_name2;
์์ ๋ง๋ t1, t2 ํ ์ด๋ธ ์ ์์๋ก, t1- t2 = 1์ด ๋๋ค
Emulate Minus Operator
-- Syntax:
SELECT
select_list
FROM
table1
LEFT JOIN table2
ON join_predicate
WHERE
table2.column_name IS NULL; -- table2์ ๊ฐ์ด ์๊ฑฐ๋ ์์ ๋๋ minus๊ฐ ์๋. nulll์ผ๋๋ง ๊ฐ์ ธ์ด
์ syntax๋ฅผ ์ ์ฉํด๋ณด๋ฉด,
SELECT -- ์ถ์ถํ ๋ฐ์ดํฐ
id
FROM -- t1 - t2 ์ค t1
t1
LEFT JOIN -- t2์ id๋ฅผ ํฉ์น ๊ฒ์ด๋ค
t2 USING (id)
WHERE -- t2์ id๊ฐ null์ธ ๊ฐ๋ง ์ถ๊ฐํ๋ค. ์๊ฑฐ๋ ์์ผ๋ฉด minus๊ฐ์๋
t2.id IS NULL;
<9> Modifying data in MySQL
1. Insert
INSERT statement allows you to insert one or more rows into a table.
INSERT INTO table(c1,c2,...)
VALUES (v1,v2,...);
Example
Create a table
CREATE TABLE IF NOT EXISTS tast(
task_id INT AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
start_date DATE,
due_date DATE,
priority TINYINT NOT NULL DEFAULT 3, --default 3
description TEXT,
PRIMARY KEY (task_id)
);
Insert
INSERT INTO tasks(title,priority) -- ํ
์ด๋ธ ์ถ๊ฐ tablename(col,col)
VALUES('Learn MySQL INSERT Statement',1);-- Values(val1, val2);
Insert using default value
์ ํ ์ด๋ธ์์ priority์ ๋ํดํธ ๊ฐ์ 3์ผ๋ก ์ง์ ํ๋ค. ๋ฐ๋ผ์ ์๋๊ฐ ๊ฐ๋ฅํ๋ค
INSERT INTO tasks(title,priority)
VALUES('Understanding DEFAULT keyword in INSERT statement',DEFAULT);
Insert Date ('YYYY-MM-DD' format)
- ์ง์ ์ ๋ ฅ : YYYY-MM-DDํํ
- CURRENT_DATE() ์ฌ์ฉ
# ๋ฐฉ๋ฒ 1:
INSERT INTO tasks(title, start_date, due_date)
VALUES('Insert date into table','2018-01-09','2018-09-15');
# ๋ฐฉ๋ฒ 2:
INSERT INTO tasks(title,start_date,due_date)
VALUES('Use current date for the task',CURRENT_DATE(),CURRENT_DATE())
2. Insert Multiple Rows
# Syntax:
INSERT INTO table_name (column_list)
VALUES
(value_list_1),
(value_list_2),...
(value_list_n);
Insert Multiple rows
value์ multiple ๊ฐ๋ค์ ์ถ๊ฐํ๋ฉด ๋๋ค
INSERT INTO tasks(title, priority)
VALUES
('My first task', 1),
('It is the second task',2),
('This is the third task of the week',3);
3. Insert into Select
# Syntax:
INSERT INTO table_name(column_list)
SELECT
select_list
FROM
another_table
WHERE
condition;
Example
Create a table:
CREATE TABLE suppliers (
supplierNumber INT AUTO_INCREMENT,
supplierName VARCHAR(50) NOT NULL,
phone VARCHAR(50),
addressLine1 VARCHAR(50),
addressLine2 VARCHAR(50),
city VARCHAR(50),
state VARCHAR(50),
postalCode VARCHAR(50),
country VARCHAR(50),
customerNumber INT,
PRIMARY KEY (supplierNumber)
);
Check Table - customers living in CA
SELECT
customerNumber,
customerName,
phone,
addressLine1,
addressLine2,
city,
state,
postalCode,
country
FROM
customers
WHERE
country = 'USA' AND
state = 'CA';
- Use Insert into... Select
INSERT INTO suppliers ( -- select์ ์์ ์ถ๊ฐ
supplierName,
phone,
addressLine1,
addressLine2,
city,
state,
postalCode,
country,
customerNumber
)
SELECT
customerName,
phone,
addressLine1,
addressLine2,
city,
state ,
postalCode,
country,
customerNumber
FROM
customers
WHERE
country = 'USA' AND
state = 'CA';
Using SELECT statement in the values list
Example
Create table
CREATE TABLE stats (
totalProduct INT,
totalCustomer INT,
totalOrder INT
);
Inswert Values
INSERT INTO stats(totalProduct, totalCustomer, totalOrder)
VALUES(
(SELECT COUNT(*) FROM products),
(SELECT COUNT(*) FROM customers),
(SELECT COUNT(*) FROM orders)
);
4. Insert Ignore
Insert ์ ์ ํตํด rows๋ฅผ ๋ํ ๋์๋, ์๋ฌ ๋ฐ์ ์ ์๋ฌด row ๋ ์์ฑ๋์ง ์๋๋ค → insert ignore์ ์ฌ์ฉํ๋ฉด ์๋ฌ๋ฅผ ๋ฌด์ํ๊ณ ์ ์์ ์ธ ๊ฐ์ ๊ฐ์ง row๋ค์ ์ถ๊ฐ๋๋ค
#Syntax
INSERT IGNORE INTO table(column_list)
VALUES( value_list),
( value_list),
...
Example
# Create Table
CREATE TABLE subscribers (
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(50) NOT NULL UNIQUE -- email ์ค๋ณต ๋ถ๊ฐ
);
# Insert Value
INSERT INTO subscribers(email)
VALUES('john.doe@gmail.com');
# Insert Values
INSERT INTO subscribers(email)
VALUES('john.doe@gmail.com'), -- email์ด ์ค๋ณต ๋ถ๊ฐ์ธ๋ฐ, ๊ฐ์ ๊ฐ์ ์ถ๊ฐ ์ ์ค๋ฅ๊ฐ ๋๋ค
('jane.smith@ibm.com');
Insert Value ์ ์ค๋ฅ : Error Code: 1062. Duplicate entry 'john.doe@gmail.com' for key 'email'
์ค๋ฅ๊ฐ ๋ฐ์ํ์๊ธฐ ๋๋ฌธ์, Jane.smith@ibm.com๋ ์ถ๊ฐ๋์ง ์๋๋ค
INSERT IGNORE INTO subscribers(email)
VALUES('john.doe@gmail.com'), -- ์ค๋ณต ๊ฐ -> warning์ด ์๊ธด๋ค. SHOW WARNGINGS;
('jane.smith@ibm.com');
Strict and Insert Ingore
Strict Mode on → insert ingore ์ฌ์ฉ ์ ์๋ฌ๊ฐ ๋ฐ์ํ๋ฉด, it tries to adjust the values to make them valid before adding the value to the table.
Example
CREATE TABLE tokens(s varchar(6)); -- create table
INSERT INTO tokens VALUES('abcdefg'); -- insert rows->error:7๊ธ์์..
# Insert Ignore Into
INSERT IGNORE INTO toekns VALUES('abcdefg'); -- g๋ ์์์ drop
ํจ์คํธ์บ ํผ์ค ํ๊ธ ์ฑ๋ฆฐ์ง ๋ฐ๋ก๊ฐ๊ธฐ๐ https://bit.ly/3FVdhDa
์๊ฐ๋ฃ 100% ํ๊ธ ์ฑ๋ฆฐ์ง | ํจ์คํธ์บ ํผ์ค
๋ฑ 5์ผ๊ฐ ์งํ๋๋ ํ๊ธ์ฑ๋ฆฐ์ง๋ก ์๊ฐ๋ฃ 100% ํ๊ธ๋ฐ์ผ์ธ์! ๋ ๋ฆ๊ธฐ์ ์ ์๊ธฐ๊ณ๋ฐ ๋ง์ฐจ ํ์น!
fastcampus.co.kr
๋ณธ ํฌ์คํ ์ ํจ์คํธ์บ ํผ์ค ํ๊ธ ์ฑ๋ฆฐ์ง ์ฐธ์ฌ๋ฅผ ์ํด ์์ฑ๋์์ต๋๋ค.
'๐ STUDY > FASTCAMPUS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| ํจ์คํธ์บ ํผ์ค ์ฑ๋ฆฐ์ง 9์ผ์ฐจ (2) | 2021.11.09 |
|---|---|
| ํจ์คํธ์บ ํผ์ค ์ฑ๋ฆฐ์ง 8์ผ์ฐจ (0) | 2021.11.08 |
| ํจ์คํธ์บ ํผ์ค ์ฑ๋ฆฐ์ง 6์ผ์ฐจ (0) | 2021.11.06 |
| ํจ์คํธ์บ ํผ์ค ์ฑ๋ฆฐ์ง 5์ผ์ฐจ (0) | 2021.11.05 |
| ํจ์คํธ์บ ํผ์ค ์ฑ๋ฆฐ์ง 4์ผ์ฐจ (0) | 2021.11.04 |
