본문 바로가기
CLASS/MYSQL

#4-1 / group by , table및 column 복제 등

by eungSe__ 2024. 6. 5.

* show full columns from table명;   : table의 상세 내용을 모두 출력
-> erd comment 볼 수 잇음 

 

⚡ [합계,평균 등]
select sum(colomn명) from table명; => 총 합계금액 출력 (단,문자일 경우 오류가 발생할 수 있음)
select avg(colomn명)  from colomn명;=> 평균
select max(colomn명)  from colomn명; => 제일 큰값 

⚡ [데이터의 범위 갯수만큼 출력하는 방법]
select * from table명 limit 배열번호,출력 갯수; => 원하는 만큼 데이터 출력

 

ex)
select * from pay limit 0,10; => 0번부터부터 10개
select * from pay limit 10,10; => 10번부터부터 10개
select * from pay limit 20,10; => 20번부터부터 10개


⚡ [ group by  - 집계함수 명령어 ] - 특정 그룹에 한하여 카운팅 및 중복값 제거

select column명,count(colomn명) from table명 group by colomn명;
(* 주의 : group에 사용한 column명으로 핸들링 해야함)

ex)
select count(pcode) from pay group by pcode; (*는 전체 , 필요한 colmn명만 작성)
select pcode,count(pcode) from pay group by pcode; //상품 코드별 갯수 출력

ex ) 
select a.bid, b.mname,count(a.bid) from basket as a join member b where a.bid=b.mid group by a.bid , b.mname;

=> 1개이상 group by 사용 시 group by colomn명, colomn명 colomn명....

 

 

 

 

[응용문제 1]

구매리스트 pay table값을 이용하여 다음과 같이 결과를 출력하는 명령어를 작성하시오

아이디,고객명,연락처,결제금액

 

=> group by  : 

select a.mid,a.mname,a.mphone,b.ppay from member as a join pay b where a.mid = b.mid group by a.mid,a.mname,a.mphone,b.ppay;

(join + group by할 경우 출력할 colomn명 group by ~ 에 모두 작성해줘야함)

 

 

⚡ [ table 복제 ]

* create table 사본table명 like 원본table명;

=> table만 복제되고 안에 column 및 data는 복제되지 않음

ex ) create table pay_backup like pay;

 

* inser into 사본table명 select * fom 원본table명;

=> 복제한 table에 해당 column 및 data도 복제해 넣음

ex ) insert into pay_backcup select * from pay;

 

* create table 사본table명( selec * from 원본table명)

=> data 및 table 복제는 되지만 key,auto_increment 복제 안됨- 위의 방법을 추천

 

⚡ [ colomn명 및 자료형 변경 ] 

alter table table명 change 기존column명 변경할column명 자료형 null(or not null);

 

ex) ea를 pay_ea로 변경

alter table pay_backup change ea pay_ea int(7) not null;

 

⚡ [ table명 변경 ] 

* mysql 8.x /  mariaDb 10.x 에서 사용

rename table 변경전table명 to 변경후table명;

ex ) rename table pay_backup to backup;

 

* 모든 버전에서 가능

alter table 변경전table명 rename 변경후table명

ex ) alter table backup rename pay2;

 

⚡ [ database에 있는 table을 다른 database로 이동 ]

rename database명.table명 to 이동할database명.table명

ex) rename table eland_db.pay2 to eland_db2.pay2;