2010-04-29 69 views
0

我运行此查询MySQL查询最新的日期

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)我只有一条记录。因此,在这种情况下,我想显示最新的职业,然后显示其他职位(最新)。但目前它只显示一行。

+0

你真的应该格式化你的代码,并把你的表在代码框。 – 2010-04-29 20:05:31

+0

我无法计算出表格的列结构。 – 2010-04-29 20:12:56

+0

这个:'AND dts =(从database1.table1中选择MAX(dts))'...将确保你只得到匹配那个dts值的记录。您需要按标准分组以适当细分dts值。 – 2010-04-29 20:28:20

回答

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”限定符和所有要善于

+0

我的查询必须选择所有行才能测试。我怎样才能让它选择所有的行,以便我可以测试?谢谢 – Autolycus 2010-04-29 21:22:51