[DB] 3-1 예제 문제

편준민's avatar
Feb 25, 2025
[DB] 3-1 예제 문제

1. ‘)’ 다음에 있는 값만 확인

substr 으로 051)381-2158 중에 381 만 확인
select tel, substr(tel, 5,3) from student;

2. ‘)’가 몇 번째 자리에 있는지 확인

instr 으로 ‘)’ 은 4번 째 자리에 있는 것을 확인 하지만 내가 필요한 것은 ‘)’ 다음 자리인 5가 필요하기 때문에 +1 을 해줌
select tel, instr(tel, ")")+1 from student;
notion image

3. ‘-’가 몇 번째 자리에 있는지 확인

똑같이 instr을 사용하여 ‘-’의 자리를 확인 후 내가 필요한 값은 ‘-’의 전 자리가 필요한 것이므로 -1 해줌
select tel, instr(tel, "-")-1 from student;
notion image

4. 1번에서 사용한 substr에 대입하기

결과가 다르게 나옴
select tel, substr(tel, instr(tel, ")")+1,instr(tel, "-")-1) from student;
notion image

5. 4번문제 해결

함수를 넣지 않고 내가 상수를 넣었을 경우에는 substr(tel, 5,3) 였기 때문에 나는 5와 3을 변수로 바꾼 것이다. 2번 문제을 확인 하였을 때는 5가 잘 나오지만 3번 문제를 확인하면 3이 아닌 7이 나오고 있다. 그래서 3을 만들기 위해서는 instr(”-”)7 - instr(”)”)4 = 3 으로 만들었다.
select tel, substr(tel, instr(tel, ")")+1, instr(tel, "-")-1 - instr(tel, ")") ) from student;
notion image

6. 이후 해당 하는 값만 * 표시로 바꾸기

중간 값의 길이를 확인하여 *로 바꿔주는 함수
repeat('*', LENGTH(substr(tel, instr(tel, ")")+1, instr(tel, "-")-instr(tel, ")")-1)))

7. 최종코드

-- 정답 select name, replace( tel, substr(tel, instr(tel, ")")+1, instr(tel, "-")-instr(tel, ")")-1), repeat('*', LENGTH(substr(tel, instr(tel, ")")+1, instr(tel, "-")-instr(tel, ")")-1))) ) from student;
notion image
 
Share article

YunSeolAn