MySQL은 쉼표(,)로 구분된 문자열 내 특정 값이 있는지 여부를 확인할 수 있는 FIND_IN_SET 함수가 있다.
다음과 같은 두 예시 테이블과,데이터가 있다고 했을 때
users 테이블 | user_id | user_name | is_active | |
1 | user1 | user1@example.com | 1 (활성화) | |
2 | user2 | user2@example.com | 1 (활성화) | |
3 | user3 | user3@example.com | 0 (비활성화) |
posts 테이블 |
post_id | author_id | title | content | tags | create_at |
1 | 1 | post_1 | Content of post 1 | mysql, database | 2022-01-01 12:00:00 | |
2 | 1 | post_2 | Content of post 2 | php, mysql | 2022-01-02 12:00:00 | |
3 | 2 | post_3 | Content of post 3 | database, sql | 2022-01-03 12:00:00 | |
4 | 2 | post_4 | Content of post 4 | mysql, programming | 2022-01-04 12:00:00 | |
5 | 3 | post_5 | Content of post 5 | programming | 2022-01-05 12:00:00 | |
6 | 3 | post_6 | Content of post 6 | mysql, sql | 2022-01-06 12:00:00 | |
7 | 1 | post_7 | Content of post 7 | database, php, sql | 2022-01-07 12:00:00 | |
8 | 2 | post_8 | Content of post 8 | mysql, php | 2022-01-08 12:00:00 | |
9 | 3 | post_9 | Content of post 9 | programming, mysql | 2022-01-09 12:00:00 | |
10 | 1 | post_10 | Content of post 10 | mysql, database | 2022-01-10 12:00:00 |
FIND_IN_SET(찾을 문자열, 문자열 목록)
찾을 문자열이 문자열 목록에 있는 경우 문자열 목록에서 찾을 문자열이 있는 경우 몇번째 위치에 있는지 위치를 반환해주는데, 없는 경우 0을 반환한다.
ex) SELECT FIND_IN_SET('banana', 'apple,banana,orange,grape') => 실행 시 2를 반환 (문자열에서 'banana'의 위치)
/* 게시글의 tags에 'myslq'이 포함되어 있고 유저 상태가 활성화 이면서 최근 작성된 글 3개 조회 */
SELECT u.user_id, u.user_name, u.email, p.post_id, p.title, p.content
FROM users u
INNER JOIN posts p ON u.user_id = p.author_id
WHERE FIND_IN_SET('mysql', p.tags) > 0 AND u.is_active = 1
ORDER BY p.created_at DESC
LIMIT 3;
위 쿼리를 실행하면 아래와 같은 조회결과를 얻을 수 있다.
user_id | user_name | post_id | title | content | |
1 | user1 | user1@example.com | 10 | post_10 | Content of post 10 |
2 | user2 | user2@example.com | 8 | post_8 | Content of post 8 |
2 | user2 | user3@example.com | 4 | post_4 | Content of post 4 |
최근댓글