如何找到所需的独特结果

时间:2013-03-19 04:48:26

标签: php mysql sql

我有两个表'主题'和'子类别'

我正在使用此查询 -

Select * from `subcategory` as s 
Inner join `topic` as f
WHERE s.`Subcategory_id` = f.`Subcategory_id

我的结果显示为

Category_id子类别_id Post_id时间

    2        2.3         4    2012-12-01
    1        1.5         5    2013-01-20
    1        1.3         6    2013-03-18

还有其他列...但我想要的是选择一个Category_id的最新Post_id和Subcategory_id ...这意味着这里类别1有两个子类别它将只选择最新的(这里是1.3)和相同的结果全部数据库变大时所有类别的时间。下一个查询是什么或者如何更改现有查询以获得我想要的结果?

3 个答案:

答案 0 :(得分:2)

SELECT TOP 1 ... ORDER BY whatever column determines "the latest"

e.g。

SELECT TOP 1 ... ORDER BY TIME DESCENDING

或者在mysql的情况下:

SELECT ... ORDER BY TIME DESCENDING LIMIT 1

答案 1 :(得分:2)

SELECT Post_Id, Subcategory_Id from subcategory as s, topic as t where 
   s.Subcategory_id = t.Subcategory_id and time = (
      SELECT Max(time) from subcategory as s1, topic as t1 where 
         s1.Subcategory_id = t1.Subcategory_id and s1.Category_id = s.Category_id
   );

我认为,这样的事情会起作用。

答案 2 :(得分:0)

使用以下查询加入主题表:

SELECT s.* FROM subcategory s
    Inner JOIN (SELECT s1.Category_id,
                 MAX(s1.time1) AS max_time
                 FROM subcategory s1
                 GROUP BY s1.Category_id) y 
ON y.Category_id = s.Category_id AND y.max_time = s.time1