SQL MAX不返回唯一记录

时间:2019-01-07 09:06:53

标签: sql select max

我在数据库中名为“ Date_Created”的字段上使用SQL MAX,从本质上讲,我使用它来为特定用户恢复最近的记录。对于所有计数大于1的用户记录,它都可以正常工作,但是当用户只有一个记录时,SQL MAX不会返回记录。“有人可以告诉我我在做什么错吗?

代码:

  "SELECT CP_Score.Credit_Score "
. "FROM CP_Score "
. "INNER JOIN phpro_users ON CP_Score.ID_No=phpro_users.ID_No "
. "WHERE phpro_users.User_ID = $userloggedin "
. "  AND CP_Score.Date_Created = (SELECT MAX(CP_Score.Date_Created) "
. "  FROM CP_Score)";

2 个答案:

答案 0 :(得分:1)

SELECT CP_Score.Credit_Score
  FROM CP_Score
 INNER JOIN phpro_users ON CP_Score.ID_No=phpro_users.ID_No
 WHERE phpro_users.User_ID = $userloggedin
   AND CP_Score.Date_Created = (SELECT MAX(cps2.Date_Created)
                                  FROM CP_Score cps2 
                                 WHERE cps2.ID_No=phpro_users.ID_No)

答案 1 :(得分:0)

如果要查找一条记录,可以将结果集限制为一条记录。使用ANSI / ISO标准语法:

SELECT s.Credit_Score
FROM CP_Score s INNER JOIN
     phpro_users u
     ON s.ID_No = u.ID_No
WHERE u.User_ID = $userloggedin
ORDER BY Date_Created DESC
FETCH FIRST 1 ROW ONLY;

某些数据库对FETCH FIRST子句的表示方式有所不同-SELECT TOP (1)LIMIT很常见。