2014-04-04 59 views
0

我有2代表這樣MySQL的2臺

PERSON

|NAME  |AGE  | 
+------------+----------+ 
|mark  |20  | 
|david  |18  | 
|john  |35  | 
|mary  |29  | 
|sophie  |32  | 

LOG

|NAME  |ACTION  |TIME_STAMP   | 
+------------+------------+----------------------+ 
|mark  |LOGIN  |2010-10-10 00:20:00 | 
|mark  |LOGIN  |2010-10-10 00:25:00 | 
|mark  |LOGIN  |2010-10-10 00:30:00 | 
|mark  |LOGIN  |2010-10-10 00:35:00 | 
|david  |LOGIN  |2010-10-10 00:30:00 | 
|david  |LOGIN  |2010-10-10 00:35:00 | 

而且希望這個

|NAME  |AGE  |TOTAL ACTIONS |TOTAL TIME CONECTED | 
+------------+----------+--------------+--------------------+ 
|mark  |20  |4    |00:15:00   | 
|david  |18  |2    |00:05:00   | 
|john  |35  |0    |00:00:00   | Or null 
|mary  |29  |0    |00:00:00   | or null 
|sophie  |32  |0    |00:00:00   | or null 

其實I H除了這個SQL,但它並沒有顯示第一個表中尚未登錄的人員。

SELECT person.name, person.age, COUNT(DISTINCT log.time_stamp), SEC_TO_TIME(MAX(TIME_TO_SEC(time_stamp))- MIN(TIME_TO_SEC(time_stamp))) 
FROM person, log 
WHERE log.name = person.name 
GROUP BY person.name; 

回答

2

嘗試使用:

SELECT person.name, person.age, COUNT(DISTINCT log.time_stamp), 
     SEC_TO_TIME(MAX(TIME_TO_SEC(time_stamp))- MIN(TIME_TO_SEC(time_stamp))) 
     FROM person 
     LEFT JOIN log ON person.name = log.name 
     GROUP BY person.name; 
+0

它的工作原理,謝謝! – Raider