简单的MYSQL查询问题

时间:2011-04-17 07:27:25

标签: mysql join

    SELECT t.thread_id, t.subject, u.username,
    COUNT(p.post_id) - 1 AS responses, 
    MAX(DATE_FORMAT(p.posted_on, '%e-%b-%y %l:%i %p')) AS last,
    MIN(DATE_FORMAT(p.posted_on, '%e-%b-%y %l:%i %p')) AS first
    FROM threads AS t
    INNER JOIN posts AS p USING (thread_id)
    INNER JOIN users AS u ON t.user_id = u.user_id
    WHERE t.cat_id = 1
    GROUP BY (p.thread_id) ORDER BY last DESC

我以为我做对了,但我的查询只返回一行,我有4行,其中t.cat_id = 1.有什么想法吗?

编辑** 样本数据 http://i56.tinypic.com/f1e449.png

现在我只得到一个结果:

1  THREAD1  USER1  8  17-Apr-11 6:22 AM  17-Apr-11 3:58 AM

我期待得到类似的东西:

1  THREAD1  USER1  8  17-Apr-11 6:22 AM  17-Apr-11 3:58 AM
2  THREAD2  USER1  8  17-Apr-11 6:22 AM  17-Apr-11 3:58 AM
3  THREAD3  USER1  8  17-Apr-11 6:22 AM  17-Apr-11 3:58 AM

2 个答案:

答案 0 :(得分:1)

可能是其中一个连接表中没有相应的行:

INNER JOIN posts AS p USING (thread_id)
INNER JOIN users AS u ON t.user_id = u.user_id

另一种可能性(与第一种不相互排斥)是分组子句折叠行。

答案 1 :(得分:0)

您选择了t.thread_id,但是按p.thread_id分组。

group by更改为

GROUP BY (t.thread_id) ORDER BY last DESC  
          ^