一些背景知识:
我正在开发一种社交网络。 有下表的DB:
users(user_id, user_name, password, etc.)
posts(post_id, user_id, post_text, post_data, etc.)
followings(relationship_id, follower_id, following_id, added_date_time)
likes(like_id, user_id, post_id, added_date_time)
comments(comment_id, user_id, post_id, comment_text, added_date_time)
问题是:
我如何实现查询,该查询将获取有关我的以下(我关注的人)最近做过的事情的信息(例如有人喜欢/评论某事)并通过date_time订购此信息数组?
我可以使用一个查询制作吗?或者我必须自己做多个查询并用PHP处理所有这些东西?
最好的方法是什么?
答案 0 :(得分:0)
您必须至少分离对喜欢和评论的查询,因为结果集不同。
否则您的查询将会显示为像:
SELECT comment_id,comment_text,added_date_time FROM comments WHERE user_id IN (SELECT following_id FROM followings WHERE follower_id={{USER_ID_FROM_USER}}) ORDER BY added_date_time
这将为您提供按日期排序的{{USER_ID_FROM_USER}}后面的人的评论。
答案 1 :(得分:0)
您可以在这样的选择联合中规范化输出
SELECT t.type, t.user_id, u.user_name, t.type_id, t.post_id, t.text, t.added_date_time
FROM (
SELECT 'posts' as type, p.user_id, p.post_id as type_id, p.post_id, post_text as text, p.added_date_time
FROM posts p
JOIN followings f ON (f.following_id = p.user_id)
WHERE f.follower_id = @user
UNION
SELECT 'comments' as type, c.user_id, c.comment_id as type_id, c.post_id, comment_text as text, c.added_date_time
FROM comments c
JOIN followings f ON (f.following.id = c.user_id)
WHERE f.follower_id = @user
UNION
SELECT 'likes' as type, l.user_id, l.like_id as type_id, l.post_id, post_text as text, l.added_date_time
FROM likes l
JOIN followings f ON (f.following.id = c.user_id)
JOIN posts p ON (l.post_id = p.post_id)
WHERE f.follower_id = @user
) as t
JOIN users u ON (t.user_id = u.user_id)
ORDER BY added_date_time DESC;
因此,您只能在一个查询中获取所有数据。
我希望它适合你。