我正在进行一项练习,希望我创建一个小型的Twitter克隆,包括用户,推文和关注系统。好吧,我想出了以下数据库结构:
CREATE TABLE tweets (
tweet_id INT NOT NULL AUTO_INCREMENT,
tweet VARCHAR(140) NOT NULL,
PRIMARY KEY (tweet_id)
) ENGINE=INNODB;
CREATE TABLE users (
user_id INT NOT NULL AUTO_INCREMENT,
user VARCHAR(255) NOT NULL,
password VARCHAR(40) NOT NULL,
email VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
) ENGINE=INNODB;
CREATE TABLE user_tweets (
id INT NOT NULL AUTO_INCREMENT,
id_user INT NOT NULL,
id_tweet INT NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY (id_tweet)
REFERENCES tweets(tweeth_id)
ON UPDATE NO ACTION ON DELETE NO ACTION,
FOREIGN KEY (id_user)
REFERENCES users(user_id)) ENGINE=INNODB;
CREATE TABLE followers (
id_user INT NOT NULL REFERENCES users (user_id),
id_following INT NOT NULL REFERENCES users (user_id),
PRIMARY KEY (id_user, id_following)
) ENGINE=INNODB;
有效吗?我错过了什么吗?也:
我对外键概念感到有些失落。 :(
答案 0 :(得分:8)
以@Karel的答案为基础, 我会使用略有不同的表:
CREATE TABLE tweets (
tweet_id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL
tweet VARCHAR(140) NOT NULL,
PRIMARY KEY (tweet_id),
FOREIGN KEY user_id(user_id) REFERENCES users(user_id)
ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=INNODB;
CREATE TABLE users (
user_id INT NOT NULL AUTO_INCREMENT,
user VARCHAR(255) NOT NULL,
/*password VARCHAR(40) NOT NULL,*/<<--- NEVER STORE A PASSWORD IN THE CLEAR!
passhash VARCHAR(40) NOT NULL,
email VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
) ENGINE=INNODB;
CREATE TABLE followers (
id_user INT NOT NULL REFERENCES users (user_id),
id_following INT NOT NULL REFERENCES users (user_id),
PRIMARY KEY (id_user, id_following)
) ENGINE=INNODB;
如何从用户中选择推文?
SELECT * FROM tweets WHERE user_id = 458
如何从用户中选择关注者?
SELECT * FROM users
INNER JOIN followers ON (users.users_id = followers.id_user)
WHERE followers.id_following = 458
如何选择用户关注的人?
SELECT * FROM users
INNER JOIN followers ON (followers.id_following = users.user_id)
WHERE followers.id_user = 458
使用SHA2哈希来比较密码。
并且不要忘记在散列中添加盐以防止彩虹攻击。
SELECT user_id
FROM users
WHERE users.user = 'OralB'
AND users.passhash = SHA2(CONCAT(users.user,'secretToothbrush'),512)
SHA1不再安全,所以我建议使用512位散列长度的SHA2。
<强>链接强>
MySQL教程:http://www.tizag.com/mysqlTutorial/
外键:http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
SHA2:http://dev.mysql.com/doc/refman/5.5/en/encryption-functions.html#function_sha2
康卡特:http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
为什么盐:What is "salt" when relating to MYSQL sha1?
答案 1 :(得分:4)
您不需要表'user_tweet',因为推文只能属于1个用户,所以在tweet-table中有'user_id'更符合逻辑
像user_tweet这样的交叉只有在存在多对多关系时才有用(例如,教师教多个班组,班组从多位教师那里获得班级)
如果你这样做,你可以通过这个sql语句选择用户的推文:
SELECT Tweet
FROM Tweets t (your table name)
WHERE t.User_ID == UserID_Whose_Tweets_you_want
您现在应该能够通过类似的查询获得关注者; D
希望你能做任何事情!