mysql查询,每行的另一个表的max()

时间:2017-06-19 14:29:02

标签: mysql sql date max

这是我的问题:

SELECT loc.id, loc.nom, loc.prenom, loc.num_tel, loc.num_fixe, bat.adresse, b.date_entree, b.date_sortie, p.date FROM locataires AS loc, bail AS b, apparts AS ap, batiments as bat, clients as cli, paye as p WHERE loc.id = b.idloc AND b.idappart = ap.id AND ap.idbat = bat.id AND bat.idcli = cli. id AND loc.id = b.idloc AND ap.id = b.idappart AND p.idloc = loc.id AND cli.email ="ben@test.be"

此查询提供:

enter image description here

但我想要每个人的最后日期(最多(p.date))

(注意:有人住在同一栋楼里,这就是为什么有些人有相同的地址)

请问好吗?

1 个答案:

答案 0 :(得分:1)

试试这个。所有其他列都Max(p.date) Group By

    SELECT loc.id, loc.nom, loc.prenom, loc.num_tel, loc.num_fixe, bat.adresse,
     b.date_entree, b.date_sortie, MAX(p.date) as Date 
    FROM locataires AS loc, bail AS b, apparts AS ap, 
    batiments as bat, clients as cli, paye as p 
    WHERE loc.id = b.idloc AND b.idappart = ap.id AND ap.idbat = bat.id 
AND bat.idcli = cli. id AND loc.id = b.idloc 
AND ap.id = b.idappart AND p.idloc = loc.id 
AND cli.email ="ben@test.be"
    Group By loc.id, loc.nom, loc.prenom, loc.num_tel, loc.num_fixe, bat.adresse,
     b.date_entree, b.date_sortie