外键求助!
我创建了一个 search.php 来查找我网站上的文章。我想做的是创建一个投票系统,根据文章的赞成票数对文章进行排序。但文章在一张表中,而投票在另一张表中。所以我需要的是投票表中的外键,它会告诉文章表它有多少票,这样 search.php 就会相应地排序
我的问题是,我将如何设置一个外键来处理这个问题? 我只是不知道如何在文章表和投票表中设置外键
I made a search.php that finds articles on my site. What I was trying to do was create a voting system that would sort the articles by how many up votes it has. But the articles are in one table and the votes are in another. So what I needed was a foreign key that would be in the voting table that would tell the article table how many up votes it has so search.php would sort accordingly
My question was, how would I set up a foreign key that would handle that?
I just dont know how to set up the foreign key in the article table and the voting table
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
表文章
表投票
如果您的表设置如上(或类似),您可以在 MYSQL 脚本中创建外键限制,如下所示:
Table Articles
Table Votes
If you have your tables set up like above (or similar) you can create a foreign key restriction in your MYSQL script as:
这些不是我会选择使用的列。
对于投票,您需要知道 a) 哪篇文章 b) 哪个用户 c) 他们投了赞成票还是反对票。因此,我将有一个 ArticleID(这是您的 Article 表的外键)、一个 UserID 和一个投票,该投票可以是 1 或 -1。然后
SELECT ArticleID, SUM(Vote) AS TotalVote FROM Votes GROUP BY ArticleID
会告诉你每篇文章的总投票数,你可以根据需要进行排序。但由于您也在搜索文章,因此您需要使用您的 ArticleID 从您的文章表到您的投票表进行左连接。请注意,在这种情况下,如果您的文章还没有投票,则
SUM(Vote)
将为NULL
,因此您可能需要使用IFNULL(SUM(Vote), 0)
代替。Those aren't the columns I would have chosen to use.
For the votes, you need to know a) which article b) which user c) whether they voted up or down. So I would have an ArticleID (which is your foreign key to your Article table), a UserID and a Vote, which would be either 1 or -1. Then
SELECT ArticleID, SUM(Vote) AS TotalVote FROM Votes GROUP BY ArticleID
would tell you the total vote for each article, and you could sort if you wanted.But since you're searching articles too, you would want to use your ArticleID to make a left join from your article table to your votes table. Note that in this case
SUM(Vote)
will beNULL
if your article has no votes yet, so you may need to useIFNULL(SUM(Vote), 0)
instead.为什么不在投票表中插入一行时更新文章的投票计数呢?
你可以像这样使用它
And why don't you just update your artices's vote count along when inserting a row to votes table?
You can use it like
由于您没有告诉我们这些表格是什么,所以我假设您有 2 个表格,其中的列与此类似:
Articles(articleId, someText, ...)
和Votes(articleId) , userId, ...)
然后将 Votes 中的articleId 设置为引用Articles 中的articleId 的外键。
Since you haven't told us what the tables are I make an answer assuming you have 2 tables with columns similar to this:
Articles(articleId, someText, ...)
andVotes(articleId, userId, ...)
Then you set the articleId in Votes to be foreign key referencing to the articleId in Articles.