SQL查询输出错误

时间:2013-03-18 10:59:34

标签: sql select join sql-order-by

我正在尝试创建一个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

这导致以下结果:

enter image description here

但实际上我想要输出的是这个,还有一个字段,除了它以及我的线程表中最新线程的thread_datetime,基于ORDER BY

enter image description here

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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