我正在制作一个类似Twitter的网站,使用MySQL作为数据库。
一个用户有多个微博,一个微博有多个回复。在我介绍提及关系之前,模式似乎很好。
当网站通知某人他已经 @mention ed时,也会显示源文本。 @mention可以在Micropost内容和回复内容中出现,我想在一个查询中获得两种类型的@mention源文本。
但我不确定应如何设计提及表架构。以下是我想到的一些想法,哪一个应该是最好的?有更好的想法吗?
user_id FOREIGN KEY users(user_id) 'the user mentioned
mention_type ENUM 1 - post, 2 - reply
post_id FOREIGN KEY posts(post_id)
reply_id FOREIGN KEY replies(reply_id)
在每一行中,post_id或reply_id都将为NULL。
查询:
SELECT IF(mention_type = 1, post_text, reply_text) AS text,
IF(mention_type = 1, 'Post', 'Reply') AS type
FROM mentions
INNER JOIN posts ON posts.post_id = post_id
INNER JOIN replies ON replies.reply_id = reply_id
WHERE mentions.user_id = @user_id
user_id FOREIGN KEY users(user_id)
mention_type ENUM 1, 2
source_id 'a post_id / a reply_id, no constraint
查询:
SELECT IF(mention_type = 1,
(SELECT post_text FROM posts WHERE posts.post_id = source_id),
(SELECT reply_text FROM replies WHERE replies.reply_id = source_id)
) AS text,
IF(mention_type = 1, 'Post', 'Reply') AS type
FROM mentions
WHERE user_id = @user_id
将发布和回复关系合并为内容关系,并为帖子添加列`parent',NULL回复的非NULL ID,表示回复的帖子。
user_id FOREIGN KEY users(user_id)
content_id FOREIGN KEY content(content_id)
查询:
SELECT content_text AS text,
IF(content_parent = NULL, 'Post', 'Reply') AS type
FROM mentions
INNER JOIN content ON content_id = content.content_id
WHERE user_id = @user_id