2017-02-25 166 views
0

This is the database I am working with我已經寫了下面的查詢來獲取最大issue_id的值。但我得到了book_id 2的issue_id 14。我想要的是當book_id爲2時獲取issue_id 16,而當book_id爲3時獲取issue_id 15等等。sql查詢不返回最大值

SELECT issue.issue_id AS issue_id, issue.issue_date, issue.student_id, books.availability, 
    CASE WHEN NOW() > DATE_ADD(issue.issue_date, INTERVAL 20 DAY) 
     THEN 10*DATEDIFF(NOW(), DATE_ADD(issue.issue_date, INTERVAL 20 DAY)) 
     ELSE 0 END AS fine_amount 
     FROM issue 
     INNER JOIN books 
     ON issue.book_id=books.book_id 
     WHERE books.book_id=2 
     HAVING MAX(issue.issue_id) 
+0

的Sql MAX實例與'HAVING'和'WHERE'見[這裏](HTTP://www.w3resource。 COM/SQL /聚集物的功能/最大-having.php)。 –

回答

1

使用ORDER BY ... LIMIT 1獲得最高值

SELECT issue.issue_id AS issue_id, issue.issue_date, issue.student_id, books.availability, 
    CASE WHEN NOW() > DATE_ADD(issue.issue_date, INTERVAL 20 DAY) 
     THEN 10*DATEDIFF(NOW(), DATE_ADD(issue.issue_date, INTERVAL 20 DAY)) 
     ELSE 0 END AS fine_amount 
     FROM issue 
     INNER JOIN books 
     ON issue.book_id=books.book_id 
     WHERE books.book_id=2 
     ORDER BY issue.issue_id DESC LIMIT 1 
+0

扭轉比較會更高效 – Strawberry