我无法理解如何处理我在SQL中想到的事情。我有书签,以及用户发布的关于它们的评论。我正在使用单个表格来表达所有评论。因此,我们在书签和评论之间存在一对多的关系。
还有另一张表,作为中间人,将每个书签与其所有评论联系起来。
有两种类型的评论。建议的书签标题和一般注释。建议的标题既有标题也有描述,而一般评论只有描述。还有一个建议标题的评级系统,因此主页可以为每个要显示的书签选择最高评分的标题。
所以,主要的事情要弄清楚。 Bookmarks表有BID和URL,还有带有CID,Title,Comment和Rating的Comments表。 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个最新的书签中的每一个选择最高评分?
答案 0 :(得分:1)
(OP自己的解决方案,与问题分开)
@LefterisAslanoglou说:
我在这里发布问题后几分钟才意识到我知道了答案。它已经困扰了我好几个小时,但这是一个简单的问题,即为每个书签获得一个具有最佳评级标题的表格,然后加入具有最新书签的所有标题的表格。
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 10
) AS a ON a.bid=bookmarks.bid
JOIN (
SELECT comments.cid, MAX(comments.rating)
AS maxrating
FROM comments
INNER JOIN booksncomms ON comments.cid=booksncomms.cid
GROUP BY booksncomms.bid
) AS b ON b.cid=comments.cid
WHERE comments.title IS NOT NULL
ORDER BY bookmarks.datecreated DESC;
答案 1 :(得分:0)
尝试
SELECT bookmarks.url, comments.title, comments.`comment`, MAX(comments.rating) rating
FROM bookmarks
INNER JOIN booksncomms
ON bookmarks.bid = booksncomms.bid
INNER JOIN comments
ON comments.cid = booksncomms.cid
WHERE comments.title IS NOT NULL
ORDER BY bookmarks.datecreated DESC, bookmarks.url
LIMIT 10