Php 在同一表格中选择不同于新的或旧的
我有一个表名为: 线程\u注释 现在,表格已按如下方式填写:Php 在同一表格中选择不同于新的或旧的,php,mysql,Php,Mysql,我有一个表名为: 线程\u注释 现在,表格已按如下方式填写: thread_comment_id thread_id user_id thread_comment thread_comment_time 1 2 1 This is a comment 2016-09-14 15:30:28 2 4 1 This is a co
thread_comment_id thread_id user_id thread_comment thread_comment_time
1 2 1 This is a comment 2016-09-14 15:30:28
2 4 1 This is a comment 2016-09-14 15:32:28
3 2 1 This is a comment 2016-09-14 15:33:28
4 5 1 This is a comment 2016-09-14 15:34:28
5 7 1 This is a comment 2016-09-14 15:35:28
6 2 1 This is a comment 2016-09-14 15:37:28
7 2 1 This is a comment 2016-09-14 15:40:28
我想在我的页面上显示最新的线程。例如:
作为第一名,我想要线程注释id7
作为第二名,我需要线程注释id5
我跳过了6,因为我不希望列表中有任何重复项
为此,我做了以下工作:
$sql = "SELECT DISTINCT thread_id FROM thread_comment ORDER BY thread_comment_time DESC"
这是一种工作(不显示任何副本)。但是这个命令没有任何意义
例如:
它像5-6-4-7等等。如果我理解正确,您希望每个线程有一行。以下是一种方法:
select tc.*
from thread_comment tc
where tc.thread_date = (select max(tc2.thread_date)
from thread_comment tc2
where tc2.thread_id = tc.thread_id
);
未在
DISTINCT
中指定在ORDER BY
中使用的列。您需要使用聚合函数和分组依据
使与众不同
工作
SELECT DISTINCT thread_id, max(thread_comment_id) FROM thread_comment GROUP BY thread_id ORDER BY max(thread_comment_id) DESC, thread_id
编辑:添加了聚合函数最大值()
另外,线程id在示例中的排序依据中不是必需的。在您的示例中,您的排序依据的列名与示例中的列名不同。这只是一个错误类型吗?编辑@Jacob Morris这是一个错误类型:)这仍然给了我一个随机顺序:/true,我忘记了聚合最大值()它首先显示的是最旧的,然后是最新的。从DESC切换到ASC dit not worked是否在某个时间点编辑线程\u注释\u时间字段?如果没有,您可以使用thread\u comment\u id:max(thread\u comment\u id)。我不确定max()如何处理日期。我要看一看。我理解代码,但它仍然给我一个奇怪的(不正确的)顺序:/I我想显示所有活动线程。(当用户在线程上添加注释时,活动)。但我不想显示双线程。