VALUES 또는 CASE를 사용해 결과 가독성 높이기

데이터 탐색기를 사용하여 쿼리를 작성할 때, 텍스트 형식 대신 코드 값이 결과에 표시되는 경우가 있습니다. 필드에는 데이터 탐색기 트리에서 키를 찾을 수 있지만, 결과를 확인하는 데에는 이 키들이 항상 유용하지는 않습니다(물론 모두 외워두셨다면話は別이지만 :slight_smile:).

이러한 코드를 더 직관적으로 보이게 하고, 다른 사람들과 더 쉽게 공유할 수 있도록 도와줄 수 있는 몇 가지 방법이 있습니다.

먼저 첫 번째 방법부터 살펴보겠습니다.

VALUES

아래의 첫 번째 쿼리는 특정 주제에 대해 사용자가 받은 모든 알림을 가져오기 위해 작성되었습니다. notification_type 코드만 출력하는 대신, VALUES를 사용하여 임시 테이블을 생성하고 각 코드를 훨씬 더 사람이 읽기 쉬운 텍스트로 매핑합니다:

-- Define parameters for user_id and topic_id
-- [params] 
-- user_id :user_id
-- topic_id :topic_id

-- Create a Common Table Expression (CTE) named ntypes
-- This CTE maps notification type names to their corresponding IDs
WITH ntypes(notification_type, notification_type_id) AS (
  VALUES
    -- Define pairs of notification types and their corresponding IDs
    ('mentioned', 1),
    ('replied',2),
    ('quoted',3),
    ('edited', 4),
    ('liked', 5),
    ('private_message', 6),
    ('invited_to_private_message', 7),
    ('invitee_accepted', 8),
    ('posted', 9),
    ('moved_post', 10),
    ('linked', 11),
    ('granted_badge', 12),
    ('invited_to_topic', 13),
    ('custom', 14),
    ('group_mentioned', 15),
    ('group_message_summary', 16),
    ('watching_first_post', 17),
    ('topic_reminder', 18),
    ('liked_consolidated', 19),
    ('post_approved', 20),
    ('code_review_commit_approved', 21),
    ('membership_request_accepted', 22),
    ('membership_request_consolidated', 23),
    ('bookmark_reminder', 24),
    ('reaction', 25),
    ('votes_released', 26),
    ('event_reminder', 27),
    ('event_invitation', 28),
    ('chat_mention', 29),
    ('chat_message', 30),
    ('chat_invitation', 31),
    ('chat_group_mention', 32),
    ('chat_quoted', 33),
    ('assigned', 34),
    ('question_answer_user_commented', 35), 
    ('watching_category_or_tag', 36),
    ('new_features', 37),
    ('admin_problems', 38),
    ('following', 800), 
    ('following_created_topic', 801),
    ('following_replied', 802),
    ('circles_activity', 900)
)
-- Query the notifications table (alias n), joining it with the ntypes CTE based on the notification_type
SELECT user_id, ntypes.notification_type, read, topic_id, created_at
FROM notifications n
JOIN ntypes
ON n.notification_type = ntypes.notification_type_id
-- Filter the notifications to only include those that belong to a specific user and a specific topic
WHERE user_id = :user_id
AND topic_id = :topic_id
-- Sort the resulting notifications in descending order by the created_at timestamp
ORDER BY created_at DESC

VALUES를 사용하는 것은 목록이 긴 경우 쿼리를 더 읽기 쉽게 만들 수 있어 유용합니다. 또한 생성된 임시 테이블을 다른 테이블과 연결할 수 있어 매우 편리합니다. 또한 CASE 문 일련의 것들과 비교했을 때 효율성을 높이는 데에도 도움이 될 수 있습니다.

이로 인해 두 번째 방법인…

CASE

대안으로, 목록이 훨씬 더 작은 경우 유사한 효과를 위해 CASE를 사용할 수도 있습니다. 다음은 post_type에 대한 예시입니다:

-- [params]
-- topic_id :topic_id

SELECT p.id AS post_id,
 -- Begin CASE statement to map post_type numerical codes to string descriptions
        CASE 
          WHEN post_type = 1 THEN 'regular'
          WHEN post_type = 2 THEN 'moderator_action'
          WHEN post_type = 3 THEN 'small_action'
          WHEN post_type = 4 THEN 'whisper'
        END
FROM posts p
WHERE p.topic_id = :topic_id
ORDER BY created_at DESC

이러한 샘플 쿼리는 단독으로 사용했을 때 큰 도움이 되지 않을 수 있지만, 원칙을 시연하기 위한 것입니다. 도움이 되길 바라며, 질문이 있다면 아래에 남겨주세요. :slight_smile:

13개의 좋아요