SQL

MYSQL 2일 - 테이블만들기

record2080 2025. 3. 9. 20:14

create table student(
name varchar(10),
age int,
adress varchar(10)
);

 

INSERT INTO student(name, age, adress)
VALUES
('홍길동', 23, '서울'),
('강길순', 24, '인천'),
('이순신', 22, '서울'),
('강감찬', 23, '인천'),
('유관순', 21, '서울');

 

update student
set age=25
where id=2;

강감찬과 유관순 나이를 20살로 변경
or, in

update student
set age=25
where in(id=4 or id=5)


update student
set age=20
where id=4 or id=5;


update student
set age=20
where id in(4,5);

-or연산자보다 in 연산자가 실행 속도가 빠르다
-in연산자 안에 서브쿼리를 넣을 수 있다

현재나이를 1살씩 업데이트

update student
set age=age+1;

 

as 별칭 설정 (alias) : 생략가능
-칼럼, 테이블, 서브쿼리 ...

select name as '이름', age as '나이' from test3;
//한글은 따옴표 붙이고 영어는 따옴표 생략 가능
mysql> select name as '이름', age as '나이' from student;
+--------+------+
| 이름   | 나이 |
+--------+------+
| 홍길동 |   24 |
| 이순신 |   23 |
| 강감찬 |   24 |
| 유관순 |   22 |
+--------+------+
-별칭을 붙여놓으면 간략하게 자료를 볼 수 있다
as구문 안에서만 as문 적용

a.name(a칼럼안에 있는 네임)

 

주의 ) 텍스트일 때는 무조건 작은따옴표
칼럼일 때나 알리아스일때는  한글이든 영어든 ' ' 상관은 없는데
영어는 보통 안 쓰고 한글은 ' '쓴다

 

주의 ) sum과 + 차이점을 기억해라!!!

 

성적이 90점 이상인 학생들을 장학금 테이블로 복사
장학금 테이블명= student_best 구조 복사하여 생성 후 복사
create table if not exists student_best
like student;

//만약 성적이 90점 이상이면 서브쿼리 사용(조건은 서브쿼리로)

insert into student_best  
(select * from student where score>=90);

 

※위치주의※

//만약 구조가 같지 않다면
insert into student_best (칼럼명)
(select  칼럼명  from student where score>=90);

insert into student_best (num,name,age)
(select  num,name,age  from student where score>=90);


+------+-----------+------+--------+---------+----------+-------+-------+---------+
| num  | name      | age  | gender | adress  | major    | score | grade | ranking |
+------+-----------+------+--------+---------+----------+-------+-------+---------+
| 1003 | leesunsin |   23 | m      | Incheon | Computer |    57 |     4 | C       |
| 1005 | sunny     |   22 | w      | Suwon   | Korea    |    97 |     3 | A       |
| 1111 | 홍길동    |   21 | m      | seoul   | computer |    89 |     2 | B       |
| 2222 | 강길순    |   21 | m      | Seoul   | English  |    87 |     2 | B       |
| 3333 | 이순신    |   23 | m      | Incheon | Computer |    57 |     4 | C       |
| 5555 | 유관순    |   22 | w      | suwon   | Computer |    97 |     3 | A       |
+------+-----------+------+--------+---------+----------+-------+-------+---------+
만약 1003번의 점수가 80으로 바뀐다고 해서 랭킹은 변하지 않는다(자동업데이트x)
만약 점수랑 랭킹으로 연결 시키고 싶으면 트리거를 사용한다
하지만, db를 건드리면 비용이 들기 때문에 주로 웹> java>db 가 일반적인 방법이다
db가 할 수 있는 일은 화면도 할 수 있고 자바도 할 수 있다
어떤 것이 효율적인지 생각하고 처리한다
1. 화면
2. 자바
3. db


sql문 연습하기

1. buy 테이블에서 customer 이름을 홍0동 변경하여 출력 => select
select customer,  insert(customer,2,1,'O') from buy;
select  insert(customer,2,1,'O') from buy;

2. product 테이블에서 price가 40000이상인 데이터만 
상품명(할인상품)으로 표시 => select
select  concat(name,'(할인상품)') from product
where price>=40000;


3. 월별 매출(price*sale_amount)합계 출력
select month(register_date),sum(price*sale_amount) as sum from product
group by month(register_date)
order by sum;

4. price가 가장 높은(가장 비싼상품) 출력
\
select max(price) from product;
\
select * from product
where price=(select max(price) from product );         //서브쿼리 이용!!!

\

5. transaction 을 사용하여 
9월에 입고된 재고 상품을 product_non 로 이동 => 미리 생성
product_non 테이블은 product와 같은 형식으로 생성
기존 product 테이블에서는 삭제
완료되면 commit;

1) non product 테이블 생성
create table if not exists product_non
like product;

2)
 start transaction 
insert into product_non
(select * from product where month(register_date)=9);
delete from product where month(register_date)=9;
commit;

6. 가장 많이 판매한 제품의 이름을 출력 => buy테이블 기준 //having조건
max(amount)

\
select product_name,sum(amount) from buy
where sum(amount=(select max(sum(amount)) from buy)
group by product_name;
\
select product_name from buy
where amount=(select max(amount) from buy)
group by product_name;
\

select max(sum) from(
select sum(price)  

 

'SQL' 카테고리의 다른 글

SQL 강의 - day3: MYSQL  (0) 2025.03.09
SQL 강의 - day2 : MYSQL  (1) 2025.03.09
MYSQL 1일 -테이블만들기  (0) 2025.03.09
SQL 강의 - day1 : MYSQL  (0) 2025.02.24
SQL 강의 day 1 - 데이터베이스 기초  (0) 2025.02.16