gpt4 book ai didi

php - mysql 'likes' 结构表

转载 作者:搜寻专家 更新时间:2023-10-30 20:10:36 24 4
gpt4 key购买 nike

我正在开发一个网站,用户可以在该网站上发布具有此表结构的文章:

CREATE TABLE IF NOT EXISTS `articles` (
`id_articles` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_users` int(10) unsigned NOT NULL,
`articles` text NOT NULL,
PRIMARY KEY (`id_articles`),
UNIQUE KEY `id_articles` (`id_articles`),
KEY `id_users` (`id_users`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

每个用户都可以“喜欢”这些文章。

下面创建“like table”的方法是否正确:

CREATE TABLE IF NOT EXISTS `articles_likes` (
`id_articles` int(10) unsigned NOT NULL,
`id_users` int(10) unsigned NOT NULL,
KEY `id_articles` (`id_articles`,`id_users`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

最佳答案

这是正确的,但您需要在 id_articles 和 id_users 上添加单独的索引(为了理智,您可能还想将列命名为“id_article”和“id_user”)。

CREATE TABLE IF NOT EXISTS `article_likes` (
`id_article` int(10) unsigned NOT NULL,
`id_user` int(10) unsigned NOT NULL,
KEY `id_article` (`id_article`),
KEY `id_user` (`id_user`)
) ENGINE=InnoDB;

您需要单独索引的原因是因为在 mysql 中,如果您在列 (A, B) 上创建索引,则该索引将用于具有 where 子句列 A 或列 A 和 B 的查询。例如,在您的情况下,如果您查询“SELECT * FROM article_likes WHERE id_user=X”,则此查询不会使用索引。一个更好的选择是在组合索引的第二列上添加一个组合索引和一个单独的索引。像这样:

CREATE TABLE IF NOT EXISTS `article_likes` (
`id_article` int(10) unsigned NOT NULL,
`id_user` int(10) unsigned NOT NULL,
KEY `id_article_user` (`id_article`, `id_user`),
KEY `id_user` (`id_user`)
) ENGINE=InnoDB;

这样您就可以在“WHERE id_user=X”、“WHERE id_article=X”、“WHERE id_article=X AND id_user=Y”等查询上获得最佳性能

关于php - mysql 'likes' 结构表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14959803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com