2012-01-24 45 views
-2

我正在嘗試從數據庫中返回所有工程師。除此之外,還有其他一些用戶信息。但我希望交流表加入最近的行,然後通過聯繫人名稱排序主要結果。SQL - 訂購左連接和主要結果

任何人都可以向正確的方向挑撥我嗎?

SELECT 
    mb.type, mb.contactname, mb.id, mb.inv_addressline2, mb.inv_addressline3, mb.signup_date, 
    fb.engineer_id, fb.job_id, fb.neg_or_pos, fb.rating, fb.author_id, 
    ac.engineer_id, ac.timestamp, ac.author_id, 
    jb.job_id, SUBSTRING(jb.job_description, 0, 200) AS `short_description`, jb.timestamp 
FROM " . MEMBERS_TABLE . " AS mb 
LEFT JOIN " . ACCEPTED . " AS ac ON mb.id = ac.engineer_id 
LEFT JOIN " . FEEDBACK . " AS fb ON ac.job_id = fb.job_id 
LEFT JOIN " . JOBS . " AS jb ON fb.job_id = jb.job_id 
WHERE mb.type = 2 
GROUP BY mb.contactname 
ORDER BY ac.timestamp DESC 

回答

0

因此,只有從時間戳是該組的最大時間的ac中選擇行;然後按聯繫人姓名排序。

這裏的每一位工程師,她最大的時間戳匹配的查詢:

SELECT engineer_id, max(timestamp) as latest 
FROM ac 
GROUP BY engineer_id; 

那麼只有選擇其行(ID,時間戳)是該表中。

+0

你是怎麼做的?歡呼 –

0

想通了中底:

SELECT 
    res.type, res.contactname, res.id, res.inv_addressline2, res.inv_addressline3, res.signup_date, 
    res.engineer_id_global, res.job_id_global, res.neg_or_pos, res.rating, res.author_id_global, 
    res.timestamp_global, res.job_description    
FROM 
    (
     SELECT 
      mb.type, mb.contactname, mb.id, mb.inv_addressline2, mb.inv_addressline3, mb.signup_date, 
      fb.engineer_id AS `engineer_id_global`, fb.timestamp AS `timestamp_global`, fb.job_id AS `job_id_global`, fb.neg_or_pos, fb.rating, fb.author_id AS `author_id_global`, 
      ac.engineer_id, ac.timestamp, ac.author_id, 
      jb.job_id, jb.job_description 
     FROM 
      " . MEMBERS_TABLE . " AS mb 
     LEFT JOIN 
      " . ACCEPTED . " AS ac 
     ON 
      mb.id = ac.engineer_id 
     LEFT JOIN 
      " . FEEDBACK . " AS fb 
     ON 
      ac.job_id = fb.job_id 
     LEFT JOIN 
      " . JOBS . " AS jb 
     ON 
      fb.job_id = jb.job_id 
     WHERE 
      mb.type = 2 
     ORDER BY 
      fb.timestamp DESC 
    ) AS res 
GROUP BY 
    res.contactname 
ORDER BY 
    res.contactname 

乾杯

編輯

上面現在的作品!

+0

不,不起作用... –

+3

也許你不應該給建議嗎? – RBarryYoung