有时,在使用数据探索器构建查询时,您会发现结果中使用的代码而不是其文本等效项。该字段通常在数据探索器树中有一个键,但这些键在结果方面并不那么有用(除非您设法记住了所有这些键
)
您可以采取一些措施来使这些结果更易于查看,并且与他人共享的范围更广。
首先……
VALUES
第一个查询创建的目的是提取用户收到的特定主题的所有通知,但它使用了 VALUES 来创建一个临时表,并将每个通知类型映射到其更易于人类阅读的对应项,而不是仅输出 notification_type 代码:
-- 定义 user_id 和 topic_id 的参数
-- [params]
-- user_id :user_id
-- topic_id :topic_id
-- 创建一个名为 ntypes 的公共表表达式 (CTE)
-- 此 CTE 将通知类型名称映射到其对应的 ID
WITH ntypes(notification_type, notification_type_id) AS (
VALUES
-- 定义通知类型及其对应 ID 的对
('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)
)
-- 查询通知表 (别名为 n),并根据 notification_type 与 ntypes CTE 进行连接
SELECT user_id, ntypes.notification_type, read, topic_id, created_at
FROM notifications n
JOIN ntypes
ON n.notification_type = ntypes.notification_type_id
-- 过滤通知,仅包含属于特定用户和特定主题的通知
WHERE user_id = :user_id
AND topic_id = :topic_id
-- 按 created_at 时间戳降序对结果通知进行排序
ORDER BY created_at DESC
当列表很长时,使用 VALUES 很有用,因为它可以使查询更易于阅读。它还允许您将新创建的临时表与另一个表链接起来,这非常方便。与一系列 CASE 语句相比,临时表还可以帮助提高效率。
这就引出了第二个……
CASE
或者,如果列表小得多,您也可以使用 CASE 来达到类似的效果。这是 post_type 的示例:
-- [params]
-- topic_id :topic_id
SELECT p.id AS post_id,
-- 开始 CASE 语句,将 post_type 数值代码映射到字符串描述
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
这些示例查询本身可能用处不大,但更多是为了演示原理。希望它们有所帮助,但如果您有任何问题,请在下方提问。 ![]()

