sql查询(在帖子的末尾)有严重的性能问题。小数据集最多需要1秒钟。我对SQL很陌生。谁能给我一些关于如何优化查询的建议?我有两个表,用户表和通知表。
用户表:
user_id,first_name,profile_image
通知表:
category,to_uid,from_id,title_id,create_time(linux timestamp)
我想通过category和title_id字段的组合返回指定to_uid组的聚合通知。有一个名为' special'的类别。如果该类别被称为“特殊”,那么我们就不应该聚合该行。如果某行的类别为“特殊”,则其from_id和title_id字段始终为NULL。
通知样本数据:
category, to_uid, from_id, title_id, create_time (linux timestamp)
like_post, 4, 3, 5, 123456
follow, 4, 3, 4, 123457
like_post, 4, 5, 5, 123478
special, 4, NULL, NULL, 123467
special, 4, NULL, NULL, 123468
预期结果:
category, to_uid, from_id, title_id, first_name_list
like_post, 4, 3,5 5, uid_3_first_name,uid_5_first_name
follow, 4, 3, 4, uid_3_first_name
special, 4, NULL, NULL, NULL
special, 4, NULL, NULL, 123468
SELECT n.category, n.to_uid, n.title_id, n.title, n.create_time,
CASE WHEN n.category <> "category1"
THEN GROUP_CONCAT(u.first_name)
END user_name_list,
GROUP_CONCAT(n.from_id) from_id_list, GROUP_CONCAT(u.profile_image) profile_image_list,
CASE WHEN n.category IN ("category2")
THEN concat_ws("_", n.title_id, n.category)
ELSE concat_ws("_", "uni", n.id, n.category)
END AS group_id
FROM notification n, user u
WHERE CASE WHEN n.category <> "category1"
THEN n.from_id = u.user_id
ELSE 1 = 1
END
AND to_uid = 20
GROUP BY group_id
ORDER BY n.create_time DESC
LIMIT 20;
答案 0 :(得分:0)
尝试使用LEFT JOIN
FROM notification n LEFT JOIN user u
ON n.category <> "category1" AND n.from_id = u.user_id
WHERE
to_uid = 20