0

我正在尝试制作一个 SQL 查询,它输出我的类别表中的每个类别。以及计算连接到类别的每个线程。现在,这很好,但是当我尝试添加一个新字段时,我需要在其中显示最新的线程日期时间,它出错了。

到目前为止,这是我的 SQL:

SELECT categories.category_name, 
       categories.category_id, 
       COUNT(threads.thread_category_id) AS 'threadCount', 
       threads.thread_datetime
FROM   categories LEFT OUTER JOIN 
       threads ON categories.category_id = threads.thread_category_id
GROUP BY categories.category_name, categories.category_id, threads.thread_datetime
ORDER BY threads.thread_datetime DESC

这导致以下结果:

在此处输入图像描述

但我真正希望它输出的是这个,还有一个字段,还有我的线程表中最新线程的 thread_datetime,基于 ORDER BY

在此处输入图像描述

我一直在尝试不同的 JOINS 以及许多其他资源。似乎找不到可行的方法。

4

3 回答 3

1

您可以使用MAX()获取每个组的最新日期。

尝试以下查询:

SELECT 
    categories.category_name, 
    categories.category_id, 
    COUNT(threads.thread_category_id) AS 'threadCount', 
    MAX(threads.thread_datetime)
FROM categories 
LEFT OUTER JOIN threads 
    ON categories.category_id = threads.thread_category_id
GROUP BY categories.category_name, categories.category_id
于 2013-03-18T11:01:27.967 回答
1

试试这个(已将日期时间从您的组移动到选择的聚合部分)

SELECT categories.category_name, categories.category_id, 
COUNT(threads.thread_category_id) AS 'threadCount', MAX(threads.thread_datetime)
FROM categories LEFT OUTER JOIN threads ON categories.category_id =     threads.thread_category_id
GROUP BY categories.category_name, categories.category_id
ORDER BY max(threads.thread_datetime) DESC
于 2013-03-18T11:03:23.967 回答
1

就像是,

SELECT
                categories.category_name, 
                categories.category_id, 
                COUNT(threads.thread_category_id) AS 'threadCount'
    FROM 
                categories
        LEFT OUTER JOIN 
                threads 
                    ON categories.category_id = threads.thread_category_id
    GROUP BY 
                categories.category_name,
                categories.category_id
    ORDER BY 
                max(threads.thread_datetime) DESC
于 2013-03-18T11:04:32.193 回答