본문 바로가기
일기장 Today's learning

2023-04-04 Sql

by 예쁜기억저장소 2023. 4. 4.

프로젝트 진행
분석 설계 

데이터를 다룬다. 데이터 모델링 

nvidia gpu 드라이버가아닌 AMD intel 

###############################################

mysql
ctrl + G 테이블 연결
database - foward engineer

cmd 관리자모드에서  데이터 불러오기
cd C:\employees
mysql -u root -p -P 3307
source employees.sql
select *from employees
select count(*) from employees
select first_name,emp_no,hire_date from employees

select emp_no,first_name,last_name,hire_date
from employees
where emp_no>498000
and hire_date >'1990-05-01'

desc employees <-descirbe

사번이 498004인 사원의 입사일자와 같은 사원의 사번 ,이름 ,입사일자 조회
select emp_no 사번,concat(concat(first_name,'-'),last_name) 이름 ,
hire_date 입사일자
from employees
where hire_date = (select hire_date
   from employees
   where emp_no=498004)  # 입사일자가 같은사람들 조회

-- 경북과 경기에 사는 사용자의 아이디, 이름 , 주소를 출력
select userid ,name ,addr
from usertbl
where addr='경북'or addr='경기' ;
-- sql 비교연산자 IN 으로 변경
select userid, name,addr
from usertbl
where addr in ('경북','경기');

-- 성이 조씨인 사용자의 이름을 출력
select name from usertbl
where name like '조%';

# employees db 에서 사원의 성에 'il이 입력된 사원의 first_name 출력
select first_name from employees
where first_name like '%li_%';

-- # 경남에 사는 사람의 키보다 큰 키를 가진 사용자의 이름 키를 출력

select name ,height,addr
from usertbl
where height >= Any(select height
 from usertbl
 where addr='경남');

order by 키 ,name desc;

#subquery의 결과가 여러행일때
           #ANY, > ALL ,IN 

select height from usertbl
where addr='경남';

select name ,height from usertbl where height >=170;
select name ,height from usertbl where height >=173;

-- employees의 dept_emp에서 부서의 종류를 출력
select distinct dept_no from employees.dept_emp;

-- 출력하는 자료의 개수를 제한 limit
select emp_no ,first_name from employees.employees
limit 10;


order by 컬럼 asc dec alias=별칭 , 숫자 다가져올수 있다
select first_name,last_name,hire_date
from employees.employees
order by 3 desc
limit 5;

SQL에서는 ORDER BY 절을 사용하여 결과를 정렬할 수 있습니다. 내림차순으로 정렬하려면 ORDER BY 절에 DESC 키워드를 사용합니다.
예를 들어, "employees" 테이블에서 급여가 높은 순으로 내림차순으로 정렬하려면 다음과 같이 SQL 쿼리를 작성할 수 있습니다.
sql
Copy code
SELECT * FROM employees ORDER BY salary DESC;
위의 쿼리는 "employees" 테이블에서 모든 열을 선택하고, "salary" 열을 기준으로 내림차순으로 정렬한 결과를 반환합니다.

-- 기존 자료로 새로운 테이블 생성
create table mymy(select userid, nameuserIDmymynew_useraddr, addr from usertbl);
select addr from new_user;
-- 기존 테이블의 구조(컬럼)은 복사하고 자료는 없는 테이블을 생성
create table new_tb (select*from usertbl where 1=2);

-- 사용자별 구매 총개수를 구함
select userid, sum(amount) '구매 총개수' --------amount 총
from buytbl
group by userid
having sum(amount)>5
order by '구매 총개수'ㅣ avg,min,max,count,count(distinct)중복은 1개만,stdev(표준편차),var_samp(분산을구한다)


-- 전체 구매자가 구매한 물품의 개수 평균
select sum(amount) / count(*) from buytbl;

-- 사용자별 최소 수량을 구매한 사용자의 아이디, 수량을 출력
select userid,amount
from buytbl

where amount=(select min(amount)from buytbl

with rollup

sql 명령어 총정리
**************************************

create
--select 
from
where like %
group by --with rollup
having
order by asc,desc--컬럼명,알리아스명 ,숫자

insert 
update 
delete
truncate

case
end
if nullif ifnull

inner join on 
join on 
left | right | full | outer join on 
cross join
self join join on #from 절의 테이블명에 반드시 alias명 부여

union , union all, not in, in
exist #하나라도 검색하면 검색종료
distinct #중복제거
ifnull(),sum(if())
amount 

insert into table명 (컬럼,..) values(값,..)
insert into table명 values(값,..)
insert into table명 values( ),(),....

update table 명 set 컬럼명 = 값, .. where 
delete from table명 where

*********************************************



create table testtbl(id int,
username char(testtbl10),
age int);
id int auto_increment primary key,

insert into testtbl (id,username,age) values(2,'김철수',30);
auto 
insert into testtbl values(NULL,'김철웅',23);
select last_insert_id(); 맨마지막거를 보여줌

alter table testtbl auto_increment=100
set @@auto_increment_increment =3; 3씩증가 #끝에 세미클론 무조건 넣어주기
values(NULL,정연,30),(NULL,나연,20) --2개 같이 넣을수 있음

-- 다른 테이블에서 자료를 가져와서 삽입
alter table testtbl modify username varchar(50);
insert into testtbl select emp_no,first_name,10
from employees.employees;

select count(*) from testtbl;

create table sampletbl(id int ,fname varchar(40),lname varchar(40))
as select emp_no,first_name,last_name from employees.employees;
select *from sampletbl;

ALTER TABLE sampletbl RENAME COLUMN emp_no TO id;
ALTER TABLE sampletbl RENAME COLUMN first_name TO fname;
ALTER TABLE sampletbl RENAME COLUMN last_name TO lname;

ALTER TABLE sampletbl DROP COLUMN fname;
ALTER TABLE sampletbl DROP COLUMN lname;
ALTER TABLE sampletbl DROP COLUMN id;

select *from sampletbl;

create table sampletbl(id int ,fname varchar(40),lname varchar(40))
as select emp_no id,first_name fname,last_name lname from employees.employees;
select *from sampletbl;

--update 테이블명 set 컬럼명 = 값, ..where 조건식;
update sampletbl set lname='없음' where Fname like 'k%';
select*from sampletbl where Fname like 'k%';

select*from buytbl;
-- price를 150% dlstkd
update buytbl set price = price *1.5;
select * from buytbl;

-- buytbl 에서 groupname 의 값이 null인 자료 검색
select * from buytbl where groupname=null; -- 연산식에 null 이 포함되면 null 반환
select * from buytbl where groupname=is null;
select * from buytbl where groupname=is not null;

drop 전체를 삭제 복구가능
truncate삭제하는것이 효율적 ,구조를 남김,rollback 되지않음

-- mysql 의 내장함수 
-- ifnull(컬럼, 출력값) --> 컬럼의 값이 존재하면 컬럼의 값을, 아니면 출력값을
select ifnull(groupname, '분류없음') "분류"
from buytbl;

-- if(식, 참, 거짓) -->  식의 결과가 참이면 참을, 거짓이면 거짓을 출력
select if(100 > 200, '참', '거짓'); --  if(식, 참, 거짓)

-- nullif(  식1, 식2 ) -->   두 식의 결과가 같으면  NULL  반환, 아니면  식1의 값 반환
select nullif(100, 100), nullif(200,100); 

-- case  컬럼 when  값1  then  출력1  when  값2  then  출력2 ... else  출력n end
select case '이십' when 1 then '일'
          when 5 then '오'
          when 10 then '십'
                       else '오류'
         end "case 모델";