【发布时间】:2021-06-26 12:06:25
【问题描述】:
我正在从头开始创建一个自定义论坛,并尝试使用一些 LEFT JOIN 查询来获取信息,例如 total posts、total threads 和大多数 recent thread。我设法获取了数据,但 recent thread 一直返回一个随机值,而不是最近的线程。
CREATE TABLE forum_categories
(`name` varchar(18), `label` varchar(52), `id` int)
;
INSERT INTO forum_categories
(`name`, `label`, `id`)
VALUES
('General Discussion', 'Talk about anything and everything Digimon!', 1),
('Deck Discussion', 'Talk about Digimon TCG Decks and Strategies!', 2),
('Card Discussion', 'Talk about Digimon TCG Cards!', 3),
('Website Feedback', 'A place to discuss and offer feedback on the website', 4)
;
CREATE TABLE forum_topics
(`name` varchar(18), `id` int, `parent_id` int, `author_id` int, date date)
;
INSERT INTO forum_topics
(`name`, `id`, `parent_id`, `author_id`, `date`)
VALUES
('My First Topic', 1, 1, 16, '2021-03-29'),
('My Second Topic', 2, 1, 16, '2021-03-30')
;
CREATE TABLE forum_topics_content
(`id` int, `topic_id` int, `author_id` int, date datetime, `content` varchar(300))
;
INSERT INTO forum_topics_content
(`id`, `topic_id`, `author_id`, `date`, `content`)
VALUES
(1, 1, 16, '2021-03-29 15:46:55', 'Hey guys! This is my first post!'),
(2, 1, 16, '2021-03-30 08:05:13', 'This is my first topic reply!')
;
我的查询:
SELECT forum_categories.name, label, forum_categories.id, COUNT(DISTINCT(forum_topics.id)) as 'topics', COUNT(DISTINCT(forum_topics_content.id)) as 'posts', SUBSTRING(forum_topics.name,1, 32) as 'thread'
FROM forum_categories
LEFT JOIN forum_topics ON forum_categories.id = forum_topics.parent_id
LEFT JOIN forum_topics_content ON forum_topics.id = forum_topics_content.topic_id
GROUP BY forum_categories.id
ORDER BY forum_categories.id, forum_topics.date DESC
我认为拥有forum_topics.date DESC 的ORDER BY 对我有用,并输出最新的线程"My Second Topic",但事实并非如此。
我有点难过,尝试了ORDER BY 的不同变体,但无济于事。
thread 不断从两个可能的结果中返回一个随机结果。
此小提琴上提供了完整的数据示例:https://www.db-fiddle.com/f/auDzUABaEpYzLKDkRqE7ok/0
期望的结果 将'thread' 始终是最新的线程,在此示例中为"My Second Topic"。然而,它似乎总是在 "My First Topic" 和 "My Second Topic" 之间随机选择。
第一行的输出应该总是:
'General Discussion' , 'Talk about anything and everything Digimon!' 1, 2, 2, 'My Second Topic'
【问题讨论】:
-
给定样本数据集,请编辑您的问题以提供所需的相应结果。
-
你为什么(试图)在表
forum_topics_content中插入一个日期时间值,它只包含一个date字段。 -
@Luuk 只是输入错误。它实际上是一个日期时间字段。我已经更新并修复了。
-
听起来像是一个“groupise-max”问题。查看添加的标签。