這是我試圖開始工作的查詢。我處於死衚衕。 SQL查詢以獲取最後回覆的用戶名和時間戳
SELECT
t.id AS topic_id,
t.title AS topic_title,
t.content AS topic_content,
t.created_at AS topic_created_at,
t.updated_at AS topic_updated_at,
t.user_id AS topic_user_id,
c.id AS comment_id,
c.content AS comment_content,
c.created_at AS comment_created_at,
max_c.username AS comment_username,
u.username AS topic_username
FROM
topics t
JOIN
(SELECT
c2.topic_id, c2.created_at, u2.username
FROM
comments c2
JOIN
users u2 ON c2.user_id = u2.id
JOIN
topics t2 ON c2.topic_id = t2.id
ORDER BY
c2.created_at desc) max_c ON t.id = max_c.topic_id
JOIN
comments c ON max_c.created_at = c.created_at
JOIN
users u ON u.id = t.user_id
ORDER BY
c.created_at DESC
很肯定的查詢,這部分是不正確的:
SELECT
c2.topic_id, c2.created_at, u2.username
FROM
comments c2
JOIN
users u2 ON c2.user_id = u2.id
JOIN
topics t2 ON c2.topic_id = t2.id
ORDER BY
c2.created_at desc
該查詢當前顯示如下。但我想通過created_at
或任何合適的組合,所以我們只能得到最新的回覆話題。
如果你能幫助這將是驚人的,我花了大約5個小時努力,到目前爲止寫這個...
我下面附上我的表遷移。
# Dump of table comments
# ------------------------------------------------------------
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` varchar(255) DEFAULT NULL,
`user_id` int(11) NOT NULL,
`topic_id` int(11) DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `comments_ibfk_2` (`topic_id`),
CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
CONSTRAINT `comments_ibfk_2` FOREIGN KEY (`topic_id`) REFERENCES `topics` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# Dump of table topics
# ------------------------------------------------------------
CREATE TABLE `topics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`content` text,
`user_id` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
CONSTRAINT `topics_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# Dump of table users
# ------------------------------------------------------------
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT 'NOT NULL',
`email` varchar(255) DEFAULT 'NOT NULL',
`password` char(60) DEFAULT 'NOT NULL',
`admin` int(11) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
爲了提高問題的質量(已經相當不錯),請添加關於您的整個陳述意圖實現的描述以及陳述部分的預期功能的描述。此外,請使用示例數據顯示錶格的結構,並可能使用語句擴展您的表格創建腳本以插入此數據。另外,請根據樣本數據顯示您希望輸出的顯示方式。另外,您可以參考您的聲明的當前輸出,但不能真正顯示該輸出。你在使用'MySQL','SQL-Server'等嗎? – toonice
那個時候用戶可以啓動一個主題,但不*發佈一個評論嗎? – toonice
我們可以假設兩個'用戶'不能同時在同一個'Topic'上發佈'Comment'嗎? – toonice