[SQL] 조건에 맞는 데이터 가져오기

WOOK JONG KIM·2022년 12월 13일
0

mysql기초

목록 보기
3/13
post-thumbnail

SELECT [컬럼 이름] FROM [테이블 이름] WHERE 조건식;

위 경우 row를 하나씩 탐색하면서 조건식에 참인 row를 찾음

type != 'bug'와 동일

SELECT [컬럼 이름] FROM [테이블 이름] WHERE [컬럼 이름] BETWEEN [조건 1] AND [조건 2];

조건 1 <= 컬럼 이름 <= 조건 2

SELECT [컬럼 이름] FROM [테이블 이름] WHERE [컬럼 이름] IN ([조건 1], [조건 2], ...);
-> [컬럼 이름] IN (A, B) 쿼리는 [컬럼 이름] = A OR [컬럼 이름] = B와 동일합(or 연산자에 비해 코드가 짧음)

Like

특정 문자열이 포함된 데이터를 선택하는 연산자

  • [컬럼 이름] LIKE [검색할 문자열] 형식으로 사용

  • 해당 컬럼 값이 [검색할 문자열]을 포함하고 있는 로우만 선택

  • [검색할 문자열] 내에 와일드카드를 사용하여 검색 조건을 구체적으로 표현할 수 있음

SELECT [컬럼 이름] FROM [테이블 이름] WHERE [컬럼 이름] LIKE [검색할 문자열];

NULL

  • 데이터 값이 존재하지 않는다는 표현

  • 0 이나 공백이 아닌 알 수 없는 값을 의미

IS NULL

데이터가 NULL인지 아닌지를 확인하는 연산자

[칼럼 이름] IS NULL(IS NOT NULL)


코드 예시

DROP DATABASE IF EXISTS pokemon;
CREATE DATABASE pokemon;
USE pokemon;
CREATE TABLE mypokemon (

number int,
name varchar(20),
type varchar(20),
height float,
weight float,
attack float,
defense float,
speed float
);

INSERT INTO mypokemon (number, name, type, height, weight, attack, defense, speed)
VALUES (10, 'caterpie', 'bug', 0.3, 2.9, 30, 35, 45),
(25, 'pikachu', 'electric', 0.4, 6, 55, 40, 90),
(26, 'raichu', 'electric', 0.8, 30, 90, 55, 110),
(133, 'eevee', 'normal', 0.3, 6.5, 55, 50, 55),
(152, 'chikoirita', 'grass', 0.9, 6.4, 49, 65, 45);

select * from pokemon.mypokemon;

USE pokemon;

SELECT type from mypokemon where name = 'eevee';

SELECT attack,defense from mypokemon where name = 'caterpie';

SELECT * from mypokemon where weight > 6;

select name from mypokemon where weight > 6 and height > 0.5;

select name as weak_pokemon from mypokemon where attack < 50 or defense < 50;

select * from mypokemon where not(type = 'normal');

select name,type from mypokemon where type IN('normal','fire', 'water','grass');

select name,attack from mypokemon where attack between 40 and 60;

select name from mypokemon where name like '%e%';

select * from mypokemon where name like '%i%' and speed < 50;

select name, height, weight from mypokemon where name like '%chu';

select name, defense from mypokemon where name like '%e' and defense < 50;

select name,attack,defense from mypokemon where ABS(attack-defense) > 10;

select name, attack+speed+defense as 'total' from mypokemon where attack+speed+defense > 150;
profile
Journey for Backend Developer

0개의 댓글