mysql查询最新日期

时间:2010-04-29 20:03:01

标签: php mysql cakephp

我正在运行此查询

SELECT sh.*,
       u.initials AS initals
  FROM database1.table1 AS sh
  JOIN database2.user AS u ON u.userID = sh.userid
 WHERE id = 123456
   AND dts = ( SELECT MAX(dts) from database1.table1 ) 
ORDER BY sort_by, category

在表1中我有这样的记录

dts                           status                    category         sort_by
2010-04-29 12:20:27        Civil Engineers          Occupation 1 
2010-04-28 12:20:27        Civil Engineers          Occupation 1 
2010-04-28 12:20:54 Married             Marital Status 2      2010-04-28 12:21:15 Smoker             Tobbaco    3
2010-04-27 12:20:27        Civil Engineers          Occupation 1 
2010-04-27 12:20:54 Married             Marital Status 2      2010-04-27 12:21:15 Smoker             Tobbaco    3
2010-04-26 12:20:27        Civil Engineers          Occupation 1 
2010-04-26 12:20:54 Married             Marital Status 2      2010-04-26 12:21:15 Smoker             Tobbaco    3

如果查看我的数据,我会按类别和sort_id选择最新的条目。但是在某些情况下如29日(2010-04-29 12:20:27),我只有一个记录。所以在这种情况下,我想显示最新的职业,然后是其他人(最新)。但目前它只显示一行。

1 个答案:

答案 0 :(得分:1)

尽量猜测你拥有的东西,无论如何都要调整你的查询,比如

SELECT 
      sh.dts,
      cast( if( preAgg1.totalPerCatSort = 1, sh.status, ' ' ) as char(20))
          as SingleStatus,
      sh.category,
      sh.sort_by, 
      u.initials AS initals 
   FROM 
      database1.table1 AS sh,
      database2.user AS u,
      ( select 
              t1.category, 
              t1.sort_by, 
              max(dts) maxdts,
              count(*) totalPerCatSort
           from 
              database1 t1
           group by 
              t1.category, 
              t1.sort_by ) preAgg1
   WHERE
         sh.userid = u.userID 
     and sh.sort_by = preAgg1.sort_by
     and sh.category = preAgg1.category
     and sh.dts = preAgg1.maxdts
     and id = 123456  ?? Should this actually be the UserID column ??
  ORDER BY 
     sort_by, 
     category 

您可能必须将“ID = 123456”应用到“preAgg1”子选项中,但同样不确定该列/表适用的ID,否则,您可以使用其他“用户”的其他日期条目“对于你正在寻找的一个候选人而言,情况并不相同......你的电话。

根据您对获取所有记录的关注,我会删除您的“和ID = 123456”限定符并且一切都应该是好的