2014-04-04 68 views
0

最大值我有2個表:人登錄如何選擇組MySQL表

CREATE TABLE people(id int,name varchar(20),surname varchar(20)); 
CREATE TABLE log(id int,log_date date); 

,我需要顯示所有用戶與他們最後的日誌。 數據測試:

INSERT INTO people VALUES (1, 'John', 'Smith'), (2, 'Elisabeth', 'Taylor'), (3, 'Peter', 'Jackson'); 
INSERT INTO log VALUES (1,'2014-02-20'),(1,'2014-02-22'),(1,'2014-02-25'),(1,'2014-03-12'),(1,'2014-04-03'),(2,'2014-02-20'),(3,'2014-03-23'),(3,'2014-03-27'),(3,'2014-04-01'); 

我有這樣的代碼,到目前爲止:

SELECT name,surname,log_date  
FROM people JOIN log USING(id) 
GROUP BY id,log_date DESC; 

,但我不知道我怎麼可以只顯示最後一個日誌爲每個用戶。

回答

1
SELECT people.id, name, surname, MAX(log_date) AS log_date FROM people INNER JOIN 
    log ON people.id = log.id 
GROUP BY people.id, name, surname 

選擇添加:

ORDER BY log_date DESC 
如果你想在結果降序日誌日期排序

設置

0
  SELECT min(name), min(surname), max(log_date) 
      FROM people p1 JOIN log l1 
      ON p1.id=i1.id 
      GROUP BY id;    

沒有測試但應該做的。