我需要获得10条最新消息,并且最后有3条评论。 我做2个查询: 1)为用户获得10条最新消息。
SELECT *
FROM news
WHERE o_uid = 17
AND o_cid = 0
ORDER BY time DESC
LIMIT 10
2)在此之后,我希望在一个查询中获得对所选新闻的所有评论。我做了" IN"由新闻ID设置以检索评论。 我写的:
SELECT c.*
FROM `comments` AS c
WHERE c.`id` >= Ifnull(
(SELECT Min(s.id)
FROM
(SELECT id
FROM comments
WHERE nid = c.nid
ORDER BY id DESC LIMIT 3) AS s), ~ 0)
AND c.`nid` IN ('17',
'16')
但这不符合错误"未知栏' c.nid'在' where子句'"。通过这个子查询,我希望在每个新闻的3个最后评论ID中检索最小ID,并在我得到评论ID为> =所选id(最后3个)的所有评论之后。 请帮助我检索每条新闻的最后三条评论。感谢。
答案 0 :(得分:0)
考虑以下内容......
DROP TABLE IF EXISTS news;
CREATE TABLE news(news_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
INSERT INTO news VALUES (1),(2),(5),(6),(7),(9);
DROP TABLE IF EXISTS comments;
CREATE TABLE comments(comment_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, news_id INT NOT NULL);
INSERT INTO comments (news_id) VALUES
(2),(2),(5),(6),(3),(3),(7),(9),(9),(9),(7),(2),(3),(9);
SELECT * FROM news;
+---------+
| news_id |
+---------+
| 1 |
| 2 |
| 5 |
| 6 |
| 7 |
| 9 |
+---------+
SELECT * FROM comments;
+------------+---------+
| comment_id | news_id |
+------------+---------+
| 1 | 2 |
| 2 | 2 |
| 3 | 5 |
| 4 | 6 |
| 5 | 3 |
| 6 | 3 |
| 7 | 7 |
| 8 | 9 |
| 9 | 9 |
| 10 | 9 |
| 11 | 7 |
| 12 | 2 |
| 13 | 3 |
| 14 | 9 |
+------------+---------+
SELECT n.*
, c.*
FROM news n
LEFT
JOIN
( SELECT x.*
FROM comments x
JOIN comments y
ON y.news_id = x.news_id
AND y.comment_id >= x.comment_id
GROUP
BY x.news_id
, x.comment_id HAVING COUNT(*) <= 3
) c
ON c.news_id = n.news_id;
+---------+------------+---------+
| news_id | comment_id | news_id |
+---------+------------+---------+
| 1 | NULL | NULL |
| 2 | 1 | 2 |
| 2 | 2 | 2 |
| 2 | 12 | 2 |
| 5 | 3 | 5 |
| 6 | 4 | 6 |
| 7 | 7 | 7 |
| 7 | 11 | 7 |
| 9 | 9 | 9 |
| 9 | 10 | 9 |
| 9 | 14 | 9 |
+---------+------------+---------+