본문 바로가기
개발 교육

11.10 수업 MySQL

by azure05 2023. 11. 10.

w3school 은 웹 개발자들이 자주 사용하는 유명한 사이트이다.

 

w3school 을 사용해 MySQL 관련 소스를 얻도록 하자. 

 

MySQL 탭에 들어가보면  "try you self" 를 클릭해 직접 쿼리문을 짜보고 실행해볼 수 있다. 

 

리액트에 대해서도 배울 수 있으니 참고하자. 

w3school로 먼저 리액트를 배워보고 책을 읽어봐도 좋을 것 같다. 

 

가장 많이 w3school에서 사용하는 탭? Bootstrap 이다. 

디자인 할 때 bootstrap 사용한다. 

 

MySQL 접속이 안되어서 애먹었다..

mysql 서버를 먼저 start 시키고, 그 다음 워크벤치에서 db를 오픈한다. (root로 접속 비번 입력 잘하기!!)

 

 

 

SELECT * FROM Test01.table01;

-- 연산
select salary+100, salary*0.1, salary+salary*0.1 from table01;

-- 컬럼의 별칭 이름을 만들기
select salary 급여, salary * 0.1 bonus from table01;
-- 컬럼의 별칭 이름을 만들기 (정석)
select salary as 급여, salary * 0.1 as bonus from table01;
select salary as 급여, salary * 0.1 as 보너스 from table01;

-- 자바에서 사용하는 문법
-- int apple = 10;
select salary as 급여, salary * 0,1 as '보apple너스' from table01;

-- 공백을 설정하기 위해 따옴표 사용
select salary '급 여', salary * 0.1 "보 너 스 " from table01;



select name, salary from table01;

-- 안좋은 방식 [프로그램은 모르고 쿼리만 할 줄 아는 사람]
select concat(name,"님의 급여는 " ,salary," 입니다. ") from table01;
-- 자바에서 얻어냄 ----> [output "홍길동300"]
-- concat은 가변변수 전달이 가능하다. 3개도 가능함!

-- 자바 개발자는 여기서 처리하는 것이 아니라 가져와서 자바에서 처리하는 것이 좋습니다.
-- mysql 비용을 올릴 수 있는 방법을 피하자. 

select 3+5 from dual;
select sysdate() from dual; -- 내장함수를 호출하는 부분

 

 

 

SELECT * FROM Test01.table02;

-- 학점을 4.5를 100으로 뒀을 때 환산 값 구하는 column 도출하기
select id,name,cast(100/4.5*point AS signed integer) as score from table02;



-- distinct 종류 카운트 하기, distinct는 조합해서 쓰이기도 함
insert into table03 values(null, '한국', 10, 100, 1,4.5);
insert into table03 values(null, '미국', 20, 200, 0,4.0);
insert into table03 values(null, '일본', 30, 300, 3,3.8);
insert into table03 values(null, '한국', 40, 400, 2.8);
insert into table03 values(null, '일본', 10, 100, 2.8);

-- 중복 제거된 요소(목록) 찾기 
select distinct name from table03; -- null인 값도 같이 띄우게끔 
select count(distinct name) from table03; -- count가 들어가는 경우 null은 세지 않는다
-- 설명서 : all default
-- select all/distinct/ 컬럼명 from 테이블네임;

-- 정렬을 해보도록 하겠습니다. [order by + 요소 + asc/desc] 사용
-- 정렬을 한다고 해서 실제 table이 변형이 되는 것은 아니다. output의 결과에만 적용되는 것이다.
select * from table02 order by name desc;
select * from table02 order by name asc;
select * from table02 order by name;

 

 

 


서브 쿼리 

join을 사용해도 되지만, join은 비용이 들기에 ! 서브쿼리를 이용하는 것이 좋다.

 

-- 서브 쿼리에 대해 배워보자.



drop table table01;
CREATE TABLE table01 (
  id	INT NOT NULL,
  name 	char(10),
  mt 	char(10),
  PRIMARY KEY (id));
  
drop table table02;  
CREATE TABLE table02 (
  id	INT NOT NULL,
  mt 	char(10),
  height int,
  PRIMARY KEY (id));
  
INSERT INTO table01 VALUES (1, '홍길동1', '북한산3');
INSERT INTO table01 VALUES (2, '홍길동2', '북한산2');
INSERT INTO table01 VALUES (3, '홍길동3', '북한산5');
INSERT INTO table01 VALUES (4, '홍길동4', '북한산3');
INSERT INTO table01 VALUES (5, '홍길동5', '북한산4');
INSERT INTO table01 VALUES (6, '홍길동6', '북한산1');
INSERT INTO table01 VALUES (7, '홍길동7', '북한산2');
INSERT INTO table01 VALUES (8, '홍길동8', '북한산4');
INSERT INTO table01 VALUES (9, '홍길동9', '북한산1');
SELECT * FROM table01;

INSERT INTO table02 VALUES (1, '북한산1', 900);
INSERT INTO table02 VALUES (2, '북한산2', 1100);
INSERT INTO table02 VALUES (3, '북한산3', 990);
INSERT INTO table02 VALUES (4, '북한산4', 1200);
INSERT INTO table02 VALUES (5, '북한산5', 850);
select * from table02; 

-- 1000미터 이상의 산을 다녀온 회원들의 명단을 출력하세요.
select name from table01
where mt in (select mt from table02 where height>=1000);

 

 

 

강사님이 설명해주신 범위 !

 

 

 

[주어진 db정보]

id, 부서번호, 이름, 연봉

 

2번째 서브쿼리에 대한 내용

drop table table01;
CREATE TABLE Test01.table01 (
  `id` INT NOT NULL AUTO_INCREMENT,
  `eno` int,
  `name` VARCHAR(45) NULL,
  `salary` INT NULL,
  PRIMARY KEY (`id`));

truncate table01;
  
INSERT INTO table01 VALUES (null, 10, 'tiger1', 100); 
INSERT INTO table01 VALUES (null, 20, 'tiger2', 200); 
INSERT INTO table01 VALUES (null, 30, 'tiger3', 300); 
INSERT INTO table01 VALUES (null, 40, 'tiger4', 400); 
INSERT INTO table01 VALUES (null, 10, 'tiger5', 500); 
INSERT INTO table01 VALUES (null, 20, 'tiger6', 600); 
INSERT INTO table01 VALUES (null, 30, 'tiger7', 700); 
INSERT INTO table01 VALUES (null, 10, 'tiger8', 800); 
INSERT INTO table01 VALUES (null, 20, 'tiger9', 350); 
INSERT INTO table01 VALUES (null, 30, 'tiger10', 999); 


-- 20번 부서의 최고 급여 보다 작은 급여를 받는 직원을 검색하세요.
-- 1. 20번 부서 급여 먼저 확인해보기
select salary from table01 where eno = 20;
select max(salary) from table01 where eno = 20; 
-- 600 이 최고 급여임을 확인하였다.

select * from table01
where salary < any(select max(salary) from table01 where eno = 20 );

-- 단, 20번 부서는 빼고 출력해주세요.(조건)
select * from table01
where salary < any(select max(salary) from table01 where eno = 20 ) and eno !=20;

 

 

 

join 조인 에 대해서 배워보자!

cross 조인 (교차 조인)

: 있을 수 있는 경우의 수대로 서로가 각각 조인을 하는 것이다. 

 

한쪽에 3개의 요소, 다른 한 쪽에 4개의 요소가 있는 상황에서 

cross join을 통해서 생기는 결과값? 12개

 

하드웨어를 살릴 것인지, 소프트웨어를 살릴 것인지

최근 저가형이 선호된다. (검색속도에 영향 받으면 품질 저하라고 평가 됨)

 

*실습 : 테이블 2개 배부받음

DROP TABLE Test01.table01;
CREATE TABLE Test01.table01 (
  id 		INT NOT NULL AUTO_INCREMENT,
  name 		VARCHAR(45) NULL,
  eno	 	INT NULL,	-- 직급번호
  salary 	INT NULL,
  PRIMARY KEY (`id`));

insert into table01 values (null, '홍길동', 20, 100); 
insert into table01 values (null, '이순신', 10, 200); 
insert into table01 values (null, '안중근', 30, 300); 
insert into table01 values (null, '임꺽정', 20, 400); 
SELECT * FROM table01;

insert into table01 values (null, '홍길동', "의적", 100); 
insert into table01 values (null, '이순신', "장군", 200); 


DROP TABLE Test01.table02;
CREATE TABLE Test01.table02 (
  id 	INT NOT NULL AUTO_INCREMENT,
  eno	int,			-- 직급번호
  nickname	 VARCHAR(45) NULL,
  PRIMARY KEY (id));
  
insert into table02 values (null, 10, '장군'); 
insert into table02 values (null, 20, '의적'); 
insert into table02 values (null, 30, '의사');
SELECT * FROM table02; 

-- 교차조인 cross join(d일반 조인 :묵시적) 
select * from table01,table02;


-- cross join (ansi join: 명시적 ) : 권고사항
select * 
from table01 
cross join table02;

-- 내부 조인 (=외부 조인이 아닌 것은 모두 내부 조인이다.)
-- 조건을 동반하는 게 원칙이다.
select * 
from table01 
inner join table02;  -- + 조건이 있어야 한다. 
-- (조건이 없어? 사용을 잘못하고 있는 것, cross join으로 진행중)

-- 등가조인 과 비등가조인
select * 
	from table01 
		inner join table02
		on table01.eno = table02.eno -- join 조건 (실행1)
where salary > 200; -- 필터 조건, 검색 조건 (실행2)


select * from table01, table02
where table01.eno = table02.eno -- join 조건 (실행1)
and salary >200; -- 필터조건, 검색조건 (실행2)


select * from table01 as t1, table02 as t2 -- 별칭이 아닌, rename이 일어난 것이다. 
where t1.eno = t2.eno -- join 조건 (실행1)
and salary >200; -- 필터조건, 검색조건 (실행2)


-- 외부 조인? (outer join 이라는 표현을 사용함)




select count(*) from table01,table02;

 

 

 

 

 

'개발 교육' 카테고리의 다른 글

11.15 DB  (2) 2023.11.15
11.13 MySQL join/서브쿼리  (0) 2023.11.13
11.9 수업 MySQL  (0) 2023.11.09
11.03 <자바FX>  (0) 2023.11.04
11.2 수업 <상속,스레드>  (0) 2023.11.03