본문 바로가기

DBMS

DBMS(5)- 문자열 함수와 union 연산자

*이 글을 읽기전에 작성자 개인의견이 있으니, 다른 블로그와 교차로 읽는것을 권장합니다.*

1. 문자열 함수

SQL 문자열 함수는 문자열 데이터를 조작하고 처리하는데 사용됩니다.

  • concat()
  • left, right()
  • substring()
  • char_length()
  • lpad(), rpad()
  • ltrim(), rtrim(), trim()
  • replace()

1-1. concat

concat은 복수의 문자열을 연결해주는 함수입니다.

# concat: 복수의 문자열을 연결해주는 함수
select concat('안녕하세요!', 'MySQL') as concat;
select * from member;
select concat(address1, ' ', address2, ' ', address3) as address
from member where userid='apple';

1줄은 concat열에 value값으로 안녕하세요! MySQL 출력, 2줄은 address열에 address1부터 address3까지의 값이 들어갑니다.

concat을 사용할 때 %의 사용방식에 대해서 기억해야 합니다. SQL에서는 %%-> % 치환, %s->SQL에선 s 치환, 즉, SQL에선 %(와일드카드) 1개가 없는 것으로 생각해야합니다. ('%%',%s,'%%') -> %s% 가 되고, SQL에서 %s%는 입력한 값을 기준으로 포함된 모든 열을 가져옵니다.  (%s는 i는 변수라고 생각하면 됩니다.) 

예를 들어, ('%%','%s','%%') 는 %s%가 되고, 값을 입력했을때 에러가 나온다면, 입력한 값을 기준으로 해당 열이 포함되지 않았기 때문입니다.

"select customer_id, name, gender, age, food_item, restaurant from customer where customer_id like concat('%%',%s,'%%')"
# SQL에서는 %%-> % 치환, %s->SQL에선 s 치환, 즉, SQL에선 %(와일드카드) 1개가 없는 것으로 생각해야함.
# ('%%',%s,'%%') -> %s% 가 되고, SQL에서 %s%는 's'문자를 포함한 모든 열을 가져옵니다.

 

1-2. left, right

left, right은 왼쪽 또는 오른쪽에서 길이만큼 문자열을 가져옵니다.

# left, right; 왼쪽 또는 오른쪽에서 길이만큼 문자열을 가져옴
select left('ABCDEFGHIJKLMN', 5);
select userid, left(userpw,2) as password from member;

1-3. substirng

substring은 문자열의 일부를 가져옵니다.

# substring(문자열, 시작위치): 시작위치부터 끝까지
# substring(문자열, 시작위치, 길이): 시작위치부터 길이만큼
select substring('ABCDEFGHIJKLMN',5) as sub;
select substring('ABCDEFGHIJKLMN',5,3) as sub;
select userid, substring('ABCDEFGHIJKLMN',5,3) as sub from member;

1-4. char_length

char_length은 문자열의 갯수를 가져옵니다. 파이썬의 len()과 같은 역할입니다.

# char_length: 문자열의 갯수 표시
select char_length('ABCDEFGHIJKLM') as cnt;
select email, char_length(email) as len from member;

1-4. lpad, rpad

lpad, rpad는 왼쪽 또는 오른쪽의 해당 길이만큼 늘리고, 빈 공간을 채울 문자열을 반환합니다.

# lpad, rpad: 왼쪽 또는 오른쪽의 해당 길이만큼 늘리고, 빈 공간을 채울 문자열을 반환
# lpad(문자열, 총길이, 채울문자열)
select lpad('ABCDEFG', 10, '0') as pad;
select userid, rpad(userid, 20 '*') as pad from member;

참고: pad는 덧씌우다 의미입니다.

1-5. ltrim, rtrim, trim

ltrim, rtrim, trim은 왼쪽, 오른쪽, 모든 공백을 제거합니다.

# ltrim, rtrim, trim: 왼쪽, 오른쪽, 모든 공백을 제거
select ltrim('    ABCDEF     ') as ltrim;
select trim('    ABCDEF     ') as ltrim;

참고: trim의 뜻은 다듬다, 손질하다의 의미입니다.

1-6. replace

replace는 문자열에서 특정 문자열을 변경합니다.

# replace: 문자열에서 특정 문자열을 변경
# replace(문자열, 대상, 바꿀 문자열)
select replace('ABCEDFG','CD', '') as repl;

2. Union(유니온)

합집합을 나타내는 집합 연산자로써, 여러 SELECT문의 결과 집합을 만드는데 사용합니다. 중복된 값을 제거하며, 같은 종류의 table(같은 column)에서만 적용 가능합니다.

사용형태: select column_이름 from table_이름 union select column_이름 from talbe_이름;

우선 테이블 생성

create table product(
	code varchar(5) not null,
    name varchar(20) not null,
    detail varchar(1000),
    price int default 0,
    regdate datetime default now()
);
insert into product values ('00001', '그래픽카드', '엄청 빨라요', 400000, now());
insert into product values ('00002', '맥북', '너무 예버요', 1400000, now());
insert into product values ('00003', '밀키트', '맛있어요', 10000, now());
insert into product values ('00004', '서버', '잘돌아요', 1000000, now());
insert into product values ('00005', '스포츠카', '빨라요', 10000000, now());

create table product_new(
	code varchar(5) not null,
    name varchar(20) not null,
    detail varchar(1000),
    price int default 0,
    regdate datetime default now()
);

insert into product_new values ('10001', '게임', '재밌어요', 91000, now());
insert into product_new values ('10002', '집', '넓어요', 50000000, now());
insert into product_new values ('10003', '고양이', '야옹', 500000, now());
insert into product_new values ('10004', '강아지', '멍멍', 400000, now());
# 두 테이블의 모든 로우가 합쳐짐
select code, name, price, regdate from product
union
select code, name, price, regdate from product_new;

# 날짜/시간이 다르기 때문에 중복 데이터가 모두 출력
select code, name, price, regdate from product
union
select code, name, price, regdate from product_new;

# union은 중복데이터를 제거
select code, name, price from product
union
select code, name, price from product_new;

# union all은 중복데이터를 출력
select code, name, price from product
union all
select code, name, price from product_new;