SQL SELECT语句MAX日期和表连接

时间:2014-11-25 15:06:41

标签: mysql sql select left-join

在MySQL中,我有两个表格如下:

         ClientTable               
    clientID    clientName            
    1           Client A              
    2           Client B             
    3           Client C             
    4           Client D             
    5           Client E              
    6           Client F              



                 NotesTable
    noteID  clientID    note    noteDate
    1           3       Test 1    12-Jun-14
    2           3       Test 2    18-Aug-14
    3           4       Test 3    23-Oct-14
    4           6       Test 4    25-May-14
    5           3       Test 5    25-Nov-14
    6           6       Test 6    16-Jul-14

我想从客户端表中选择所有客户端,并且在客户端存在备注的情况下,选择最新备注条目的日期。如果客户端不存在任何注释,则为noteDate返回null。期望的结果设置如下:

    client ID   clientName  latestNoteDate  
    1           Client A    null    
    2           Client B    null    
    3           Client C    25-Nov-14   
    4           Client D    23-Oct-14   
    5           Client E    null    
    6           Client F    16-Jul-14   

任何帮助表示赞赏,我尝试了一些使用嵌套的Select with MAX(noteDate)和各种左连接的选项,但似乎无法正确使用。

5 个答案:

答案 0 :(得分:2)

为什么所有子查询?

select ct.clientID, ct.clientName,max(nt.noteDate) latestNoteDate
from ClientTable  ct
left outer join NotesTable nt
on ct.clientID = nt.clientID 
group by ct.clientID, ct.clientName

答案 1 :(得分:1)

您可以将outer join与子查询一起使用:

select c.clientid, c.clientname, n.latestnotedate
from client c
   left join (
       select clientId, max(noteDate) latestnotedate
       from notes
       group by clientId
   ) n on c.clientId = n.clientId

这假定max(noteDate)最新备注条目。如果情况并非如此,那么很容易使用noteid代替,然后只需添加一个额外的联接。

答案 2 :(得分:0)

看起来像是使用子查询的好地方。尝试类似:

select c.id, c.name, n.latestNoteDate from client c
left join
(select clientid, MAX(notedate) as latestNoteDate from note
group by clientid) as n on n.clientid = c.id

关键是,首先从notes表中找到你想要的数据,然后用它来加入客户数据。

答案 3 :(得分:0)

尝试使用以下代码,该代码使用相关的子查询。

SELECT ct.clientID,
       ct.clientName,
       (SELECT MAX(noteDate)
        FROM   notesTable nt
        WHERE  nt.clientID = ct.clientId)
FROM   clientTable ct

答案 4 :(得分:0)

select clienttable.clientID, clienttable.clientName, notes.noteDate
left outer join NotesTable notes on notes.clientID = clienttable.clientID and noteDate = (select      max(noteDate) from NotesTable where notes.clientID = clienttable.clientID)

如果没有注释条目,它将返回null。

OR

select clienttable, clientID, clienttable.clientName, (select max(noteDate) from NotesTable where notes.clientID = clienttable.clientID) noteDate