简体   繁体   English

在同一个表中选择与新旧旧不同

[英]Select Distinct from new tol old in same table

I have one table named: thread_comment我有一张表: thread_comment

Now the table is getting filled as followed:现在表格被填满如下:

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

I want to show the newest threads to my page.我想在我的页面上显示最新的主题。 for example:例如:

as number one i want thread_comment_id 7 as number two i want thread_comment_id 5作为第一我想要 thread_comment_id 7作为第二我想要 thread_comment_id 5

I skipped 6 because i don't want any duplicates in the list.我跳过了6,因为我不希望列表中有任何重复项。

In order to do so i did the folowing:为了做到这一点,我做了以下工作:

$sql = "SELECT DISTINCT thread_id FROM thread_comment ORDER BY thread_comment_time DESC"

This is kind of working (Not showing any duplicates).这是一种工作(不显示任何重复项)。 However the order does not make any sense...但是这个命令没有任何意义......

For example:例如:

It goes like 5 - 6 -4 - 7 etc...它就像 5 - 6 -4 - 7 等等......

The column used in the ORDER BY isn't specified in the DISTINCT . ORDER BY使用的列未在DISTINCT指定。 You need to use an aggregate function and GROUP BY to make the DISTINCT work.您需要使用聚合函数GROUP BY来使DISTINCT工作。

SELECT DISTINCT thread_id, max(thread_comment_id) FROM thread_comment GROUP BY thread_id ORDER BY max(thread_comment_id) DESC, thread_id

EDIT: added aggregate func max() Also thread_id is not mandatory in the ORDER BY编辑:添加聚合 func max() 此外,在ORDER BY也不需要 thread_id

It I understand correctly, you want one row per thread.我的理解是正确的,每个线程都需要一行。 Here is a way to do this:这是一种方法:

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
                       );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM