仅显示一对多选择中的最佳结果
我无法理解如何处理我在 SQL 中想到的东西。我有书签以及用户发布的关于它们的评论。我对所有评论使用一个表。所以我们的书签和评论之间是一对多的关系。
还有另一个表,充当中间人,将每个书签与其所有评论链接起来。
评论有两种类型。建议的书签标题和一般评论。建议的标题既有标题又有说明,而一般评论只有说明。还有一个针对建议标题的评级系统,以便主页可以为每个书签选择评级最高的标题来显示。
所以,主要的事情要弄清楚。其中有包含 BID 和 URL 的书签表,以及包含 CID、标题、评论和评级的评论表。 BooksNComms 是它们之间的连接表。
SELECT comments.title, comments.comment
FROM comments
INNER JOIN booksncomms ON comments.cid=booksncomms.cid
WHERE booksncomms.bid=1
AND comments.title is not null
ORDER BY comments.rating
LIMIT 0, 1;
上述方法可以为某个 BID 获取最佳标题和描述(评论)。我想做的是使上述工作适用于 10 个最新书签。
SELECT bookmarks.url, comments.title, comments.`comment`, comments.rating
FROM bookmarks
INNER JOIN booksncomms
ON bookmarks.bid=booksncomms.bid
INNER JOIN comments
ON comments.cid=booksncomms.cid
JOIN (
SELECT bookmarks.bid
FROM bookmarks
ORDER BY bookmarks.datecreated DESC
LIMIT 1
)
AS a
ON a.bid=bookmarks.bid
WHERE comments.title IS NOT NULL
ORDER BY bookmarks.url;
上面给出了 10 个最新书签的所有标题。
有没有办法可以为 10 个最新书签中的每一个只选择评级最高的标题?
I'm having trouble getting my head around how to handle something I've thought of in SQL. I have bookmarks, and comments that the users posted about them. I'm using a single table for all comments. So we have a one-to-many relationship between the bookmarks and the comments.
There is another table, acting as the middle-man, linking each bookmark to all its comments.
There are two types of comments. Suggested titles for the bookmark, and general comments. Suggested titles have both a title and a description, while general comments have only a description. There's also a rating system for the suggested titles, so that the home page can pick the top-rated title for each bookmark to display.
So, main things to make clear. There's the Bookmarks table with BID and URL, and also the Comments table with CID, Title, Comment, and Rating. The BooksNComms is the connecting table between them.
SELECT comments.title, comments.comment
FROM comments
INNER JOIN booksncomms ON comments.cid=booksncomms.cid
WHERE booksncomms.bid=1
AND comments.title is not null
ORDER BY comments.rating
LIMIT 0, 1;
The above works in getting the best Title and Description (Comment) for a certain BID. What I want to do is make the above work for, say, the 10 newest bookmarks.
SELECT bookmarks.url, comments.title, comments.`comment`, comments.rating
FROM bookmarks
INNER JOIN booksncomms
ON bookmarks.bid=booksncomms.bid
INNER JOIN comments
ON comments.cid=booksncomms.cid
JOIN (
SELECT bookmarks.bid
FROM bookmarks
ORDER BY bookmarks.datecreated DESC
LIMIT 1
)
AS a
ON a.bid=bookmarks.bid
WHERE comments.title IS NOT NULL
ORDER BY bookmarks.url;
The above gives me all titles for the 10 newest bookmarks.
Is there a way I can select only the highest rated title for each of the 10 newest bookmarks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(OP自己的解决方案,从问题中分离出来)
@LefterisAslanoglou 说:
(OP's own solution, split off from the question)
@LefterisAslanoglou says:
尝试
Try