정구리의 우주정복

[MySQL] mysql 명령어들 정리 본문

STUDY/K-DIGITAL

[MySQL] mysql 명령어들 정리

Jungry_ 2022. 9. 22. 16:42
반응형

친절한 게시글은 아닙니다 완전 초보는 이해하기 어려울 수 있어요 

 

https://www.w3schools.com/mysql/mysql_intro.asp

 

MySQL Introduction

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

https://www.w3schools.com/mysql/trymysql.asp?filename=trysql_select_where 

 

MySQL Tryit Editor v1.0

WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, usin

www.w3schools.com

여기서 연습할테야 

 

 

 

What is RDBMS ? 

RDBMS stands for Relational Database Management System.
RDBMS is a program used to maintain a relational database.
RDBMS is the basis for all modern database systems such as MySQL, Microsoft SQL Server, Oracle, and Microsoft Access.
RDBMS uses SQL queries to access the data in the database.

What is SQL ? 

SQL is the standard language for dealing with Relational Databases.
SQL is used to insert, search, update, and delete database records.

 

테이블 : 객체를 테이블 형태(열과 행)로 저장할 수 있는 것 

각 튜플들이 유일한 값인것을 기대한다 , 유일하지 않으면 쓸모없는 데이터로 취급한다 (ex 동일한 고객정보) 

 

테이블들 끼리 서로 참조할 수 있기 때문에 관계형 데이터 베이스라고 한다  . 제약조건에 의해 관계를 보장해준다. (관계가 깨지지 않도록 변화가 발생하면 같이 바꿔주고 없으면 알려주고 등등등)

 

 

 

select

The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
select *colunm1,colunm2. . .  from table_name;

 

desc table_name;

=> 테이블 내의 필드들을 확인하는 방법 

 

Null no 인애는 null 이면 안된다 !

 

관계형 DB 를 사용하는 이유

 

이렇게 다양한 방법으로 출력할 수 있다. 하지만 where 을 join 할때 쓰면 구문이 복잡해지므로 join 명령어는 따로 쓰자 !!

 

where 을 사용했을 때와 동일한 결과를 출력한다 

 

이렇게도 써볼 수 있다 

이렇게 관계형 db 를 사용하면 서로 다른 두 DB 를 참조하고 사용할 수 있다 !!!

 

 

WHERE

It is used to extract only those records that fulfill a specified condition. (특정한 조건을 만족하는 레코드만 사용한다)
SELECT * FROM Customers WHERE Country='Mexico';

문자열 타입은 따옴표를 써줘야한다 !!! 잊지말것

사이에 and 를 써주면 둘 다 성립하는 결과를 출력하게 된다
Between 은 사이에 있는 애들을 찾아준다

 

 

AND,OR,NOT

The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND are TRUE
The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.

or이 우선순위가 있어 결과가 카테고리 id 가 5인애들이 다 나오고 and 연산을 진행하게 된다 (괄호를 쳐서 정해주면 해결가능)

ORDER BY

The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

기본 값은 오름차순이고 내림차순으로 정렬하고 싶으면 desc 써주면 된다 !!!!

 

ordr by 는 출력을 다 하고 정렬하는 것이기 때문에 중간에 조건절을 넣어줄 수 있다 

select * from Customers WHERE CustomerID between 35 and 40 ORDER BY Country DESC;

이렇게도 사용 가능 

 

 

LIKE

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign (%) represents zero, one, or multiple charactersThe underscore sign (_) represents one, single character
The percent sign and the underscore can also be used in combinations!

검색을 위해서 사용한다 ! where 과는 다르게 column 에서 특정 패턴을 찾는다 

select * from Customers where CustomerName like 'a%';

customerName 이 a로 시작하는 애 !

select * from Customers where CustomerName like 'b_______';

customerName 이 b로시작하고 글자수는 8글자인 (_ 가 7개 적혀있음) 애 !

 

이렇게 두 종류의 와일드 카드를 쓸 수 있다 

select * from Customers where CustomerName like '_r%';

두번째 글자가 r 인 모든 애들 !

이렇게 와일드 카드는 혼용해서 사용 가능하다 

 

 

IN

The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.

 

where 에 구체적인 조건을 지정해 줄 수 있는 in !! in 은 기본적으로 or 처럼 동작한다 

SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');

Country 에 대한 정보 중 Gwemany, France , UK 인 사람들만 찾는 것이다 !!!!

 

서브쿼리를 사용한 IN (서브쿼리 안에는 결과가 한개만 나와야 하므로 select 를 두개 넣어준다거나 하면 안된다)

Country 가 프랑스인 사람이 주문한 내역
SELECT * FROM Orders WHERE CustomerID IN (SELECT CustomerID FROM Customers WHERE Country='France');
SELECT o.*,c.Country FROM Orders o INNER JOIN Customers c USING (CustomerID) WHERE c.Country ='France';

동일한 결과 출력하는 거를 join 사용해서 한거 

 

SELECT * FROM Customers WHERE Country IN (SELECT Country FROM Suppliers);
SELECT * FROM Customers WHERE Country IN (SELECT DISTINCT Country FROM Suppliers);

중복 제거는 DISTINCT

 

 

Aliases (AS)

Aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.

가명을 지어줄 수 있다 !!

근데 as 로 가명을 정해주면 o.OrderID 이렇게 해줘야하짐 원래 이름인 Orders.OrderID 이렇게 하면 에러가 난다 

 

 

 

CREATE TABLE

CREATE TABLE Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255)
);

입력한 순서 대로 칼럼이 생성되게 되니까 순서와 어떤 타입인지를 잘 지정해주자 

 

INSERT INTO 

INSERT INTO table_name
VALUES (value1,value2,value3,. . . );

table 에 선언해줬던 순서대로 values 를 넣어줘야한다 (바로 위 create 했던걸 보면 personID , LastName, Firstname . . 이 순서로 적어줘야한다)

 

DELETE

DELETE FROM table_name WHERE condition;

where 절을 넣어주지 않으면 다 삭제되니까 꼭 넣어줘야한다 

 

 

 

MIN() MAX() , 집계 함수

The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.

집계함수의 특징은 결과가 하나만 나오는 것이다 

SELECT MIN(Price), MAX(Price) FROM Products;

하지만 집계함수랑 관계 없는것은 연이어 쓰면 안된다 

SELECT MIN(Price), Price FROM Products;

집계 함수와 관련 없는 Price 를 쓰게 되면 

이렇게 결과가 나오는데 저기서 Price 는 min 이 아니고 그냥 맨 처음에 있는 관련없는 값이 나오게 된다 

SELECT * FROM Products WHERE Price =(SELECT MAX(Price) FROM Products);

최대 값을 찾고싶다면 이렇게 서브쿼리를 사용해서 할 수 있다 

SELECT * FROM Products WHERE Price BETWEEN (SELECT MIN(Price) FROM Products) AND (SELECT AVG(Price) FROM Products);

between 을 써서 가격이 최소인거부터 평균까지 출력시켜볼 수도 있다 

 

 

그 밖의 집계 함수들에는 min,max,sum,avg,count 등이 있다 

SELECT MIN(Price), MAX(Price),SUM(Price),AVG(Price),COUNT(Price) FROM Products;

 

 

 

SELECT * FROM OrderDetails WHERE ProductID IN (SELECT ProductID FROM Products WHERE Price > (SELECT AVG(Price) FROM Products));

이렇게 긴거 작성할 때 뒤에서부터 생각하는 습관을 길러봅시다용 

 

 

GROUP BY

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.

group by 는 같은것들을 묶을때 그것들을 집계할 수 있음 Distinct 는 그냥 같은거만  제거 

SELECT COUNT(Country) , Country FROM Customers GROUP BY Country ORDER BY Country;

집계함수를 사용한 모습 !! 

SELECT COUNT(SupplierID),SUM(Price),MIN(Price),MAX(Price),SupplierID FROM Products GROUP BY SupplierID;

 

Having

The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.

Where 키워드는 집계함수를 사용할 수 없기 때문에 Having 이 추가되었다 

SELECT COUNT(CustomerID),Country FROM Customers WHERE Country > "Brazil"
GROUP BY Country
HAVING COUNT(CustomerID)>5
ORDER BY COUNT(CustomerID);

where 까지 해서 결과를 도출 한 후 group by 를 하고 group by 한것의 조건을 having 으로 검색하고 그것을 order by 로 정렬한다 

반응형
Comments