2010-04-29 71 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