获取具有最新日期的所有记录[ERROR]

时间:2018-11-03 06:17:38

标签: mysql sql

我有此表,我想返回所有包含最新数据的记录的名字和父亲名称,只要插入新的最新日期以返回该记录,就应该是动态的。 我已经尝试过

SELECT rh.firstname, rh.fathername, rh.bloodonation_date
FROM personprofile rh,
  (SELECT MAX(bloodonationdate) AS maxdate, firstname
   FROM report_history
   GROUP BY firstname) maxresults
WHERE rh.firstname= maxresults.firstname
AND rh.bloodonation_date= maxresults.bloodonation_date;  

所以如果我有这张桌子

firstname, fathername,bloodonation_date
--------------------------
Ahmed     issa   2018-12-24
Noora     issa   2018-12-21
Joseph    John   2018-12-24
Ash       Scott  2018-12-24
Isacf     jaack  2018-12-24
Ashley    Make   2018-12-24
James     Ma     2018-12-20
cd        cd     2018-12-24
cde       cde    2018-12-24
Marc      Mac    2018-12-16
Noora     Ahmed  2018-12-15
Rabeew    fbdb   2018-11-15

如何获得退货

firstname, fathername,bloodonation_date
--------------------------
Ahmed     issa   2018-12-24
Joseph    John   2018-12-24
Ash       Scott  2018-12-24
Isacf     jaack  2018-12-24
Ashley    Make   2018-12-24
cd        cd     2018-12-24

2 个答案:

答案 0 :(得分:1)

您可以尝试使用相关子查询。

模式(MySQL v5.7)

CREATE TABLE T(
   firstname VARCHAR(50),
    fathername VARCHAR(50),
bloodonation_date DATE
);



INSERT INTO T VALUES ('Ahmed','issa','2018-12-24');
INSERT INTO T VALUES ('Noora','issa','2018-12-21');
INSERT INTO T VALUES ('Joseph','John','2018-12-24');
INSERT INTO T VALUES ('Ash','Scott','2018-12-24');
INSERT INTO T VALUES ('Isacf','jaack','2018-12-24');
INSERT INTO T VALUES ('Ashley','Make','2018-12-24');
INSERT INTO T VALUES ('James','Ma','2018-12-20');
INSERT INTO T VALUES ('cd','cd','2018-12-24');
INSERT INTO T VALUES ('cde','cde','2018-12-24');
INSERT INTO T VALUES ('Marc','Mac','2018-12-16');
INSERT INTO T VALUES ('Noora','Ahmed','2018-12-15');
INSERT INTO T VALUES ('Rabeew','fbdb','2018-11-15');

查询#1

SELECT *
FROM T 
WHERE bloodonation_date = (
  SELECT  MAX(bloodonation_date) 
  FROM T                       
);

| firstname | fathername | bloodonation_date |
| --------- | ---------- | ----------------- |
| Ahmed     | issa       | 2018-12-24        |
| Joseph    | John       | 2018-12-24        |
| Ash       | Scott      | 2018-12-24        |
| Isacf     | jaack      | 2018-12-24        |
| Ashley    | Make       | 2018-12-24        |
| cd        | cd         | 2018-12-24        |
| cde       | cde        | 2018-12-24        |

View on DB Fiddle

答案 1 :(得分:0)

您可以在此处使用子查询:

从个人资料中选择*,其中 bloodonation_date =(从个人资料中选择max(bloodonation_date)个) 按1排序 ,Check solution here