Web应用程序PHP,Mysql。用户可以撰写文章。如何构建允许用户订阅(跟随)其他用户文章然后查看订阅用户添加的最后文章列表的算法?算法必须扩展,以便一个用户可以订阅10 000个用户,10 000个用户可以订阅一个用户,所有部分都可以快速工作 - 添加新文章和用户查找订阅用户的最后文章时。
答案 0 :(得分:1)
create table `user`(
`id` INT(10) PRIMARY KEY NOT NULL AUTO_INCREMENT
);
create table `subscribes_to` (
`subscriber_user_id` INT(10) NOT NULL,
`subscribed_to_user_id` INT(10) NOT NULL, # Receiver of the subscription
PRIMARY KEY(`subscribe_user_id`, `subribed_to_user_id`),
KEY `subscriber(`subscribe_user_id`),
KEY `subscribed(`subscribed_to_user_id`);
);
# Users subscribed to role 100
SELECT distinct u.* FROM user u
JOIN subscribes_to st ON st.subscriber_user_id = u.id
WHERE
st.subscribded_to_user_id = 100;
# User 100's subsriptions
SELECT distinct u.* FROM user u
JOIN subscribes_to st ON st.subscribded_to_user_id = u.id
WHERE
st.subscriber_user_id = 100;
显示与文章关系的附加架构:
文章(
id
int(10)UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
title
VARCHAR(255),
body
文字,
date_created
DATETIME,
date_updated
DATETIME,
author_user_id
int(10)
);
# Create new article
INSERT INTO `article` VALUES (NULL, "Hello", "This is the body", NOW(), NOW(), 1);
# Find the last 10 articles posted that user 15 suscribes to
# the author of
SELECT a.* FROM article a
JOIN user ON u.id = a.author_user_id
JOIN subscribes_to st ON st.subscribed_to_user_id = u.id
WHERE st.subscriber_user_id = 15 ORDER BY a.date_created DESC LIMIT 10;