728x90
insert, auto_increment, insert into-select, update, delete
Insert : 데이터 입력
Use market db;
create table hongong1 (toy_id, toy_name char(4), age int);
insert into hongong1 values (1, '우디', 25);
Auto_increament : 자동 증가
열을 정의할 때 1부터 증가하는 값을 입력해준다. Insert에서는 해당 열이 없다고 생각하고 입력하면 된다.
단, 주의할 점은 auto_increament로 지정하는 열은 꼭 pk로 지정해줘야한다.
create table hongong2(
toy_id int auto_increament primary key,
toy_name char(4),
age int);
테이블을 만들었으니 데이터를 입력해보자
insert into hongong2 values (null, '보핍', 25);
insert into hongong2 values (null, '슬링키', 22);
insert into hongong2 values (null, '렉스', 21);
select * from hongong2;
null로 데이터를 넣은 toy_id 열은 자동으로 1씩 증가한다
숫자가 어디까지 증가했는지 궁금할 때
select last_insert_id();
auto_increament로 입력되는 다음 값을 100부터 시작하도록 변경하고 싶을 때
alert table hongong2 auto_increament=100;
insert into hongong2 values(null, '재남', 35);
select * from hongong2;
1000부터 시작하고 3씩 증가시킬 수도 있다.
create table hongong2(
toy_id int auto_increament primary key,
toy_name char(4),
age int);
alter table hongong3 auto_increament=1000; --> 시작값은 1000지정
set @@auto_increament_increament=3; -> 증가값은 3으로 지정
insert into ~ select
많은 양의 데이터를 하드타이핑으로 입력하려면 한참 걸릴거다. 다른 테이블에 이미 데이터가 입력되어 있다면
insert into ~ select 구문을 사용해 해당 테이블의 데이터를 가져와서 한번에 입력하자
insert into 테이블이름 (열_열이름1, 열_이름2, ...)
select 문 ;
주의 점은 select 문의 열 개수는 insert 할 테이블의 열 개수와 같아야 한다.
실습
city 테이블의 개수 조회
select count(*) from world.city;
world.city 테이블 구조 살펴보기
desc world.city
데이터 5건만 조회
select * from world.city limit 5;
도시 이름 과 인구를 가져와보기
create table city_popul (city_name char(35), population int);
world.city 내용은 city_popul 테이블에 입력해보기
insert into city_popul
select Name, population from world.city;
update : 데이터 수정
기본 문법
update 테이블이름
set 열1=값1, 열2=값2, ...
where 조건
💡 워크벤치에서는 기본적으로 update 와 delete를 허용하지 않아서 설정을 변경해야한다
1. 열려있는 쿼리창 닫기
2. edit → preference 메뉴 실행
3. workbench preference창의 sql editor에서 ‘safe updates’를 체크 해제 한후 ok 버튼
4. 클릭워크벤치 재시작
실습
city_popul 테이블의 도시 이름 중에서 seoul을 ‘서울’로 변경해보겠다.
use market_db;
update city_popul
set city_name = '서울'
where city_name = 'Seoul';
select * from city_popul where city_name = '서울';
필요하다면 한꺼번에 값을 수정할 수도 있다.
update city_popul
set city_name = '뉴욕', population = 0
where city_name = 'New York';
select * from city_popul where city_name = '뉴욕';
주의점
update 쿼리를 실행할 때 where 문이 없이 사용하면 모든 행의 값이 변경되니 꼭 주의해서 사용하자
반응형
delete : 행 삭제
기본 문법
delete from 테이블이름 where 조건;
실습
city_popul 테이블에서 New로 시작하는 도시를 삭제하기 위한 쿼리문
delete from city_popul
where city_name like "New%';
만약에 같은 조건에서 상위 5개만 지우고 싶을 때
delete from city_popul
where city_name like "New%';
limit 5;
반응형
'데이터' 카테고리의 다른 글
두 테이블을 묶는 조인 (0) | 2024.01.22 |
---|---|
MySQL 데이터 형식 (0) | 2024.01.20 |
깊게 알아보는 select 문 (0) | 2024.01.16 |
SELECT-FROM-WHERE (0) | 2024.01.09 |
데이터베이스 개체 (0) | 2023.12.30 |