2017-10-08 25 views
0
create procedure fine() 
begin 
declare a integer(10); 
declare b integer(10); 
declare c integer(10); 
declare d integer(10); 
declare cal_fine cursor for select book_id,datediff(return_date,issue_date) 
from return_book where datediff(return_date,issue_date)>10; 
open cal_fine; 
myloop:loop 
fetch cal_fine into a,b; 
set c=(b-10)*5; 
update return_book set fine=c where book_id=a; 
end loop; 
close cal_fine; 
end; 

我有這段代碼找到很好,但問題是,我的issue_date不在return_book表中,所以我必須加入issue_book和return_book但是那麼如何使用datediff功能? PLZ幫我如何使用datediff功能加入

+0

更新語句來實現什麼是你的代碼看起來像聯接到issue_book? –

+0

@ P.Salmon聲明cal_fine光標選擇ib.issue_date,rb.return_date從return_book RB,issue_book IB其中rb.book_id = ib.book_id 但後來我該怎麼辦有關DATEDIFF? 這個? :datediff(return_date,issue_date)from return_book,其中 datediff(return_date,issue_date)> 10; – N97

+0

如果您的問題是我是否需要重複where條款中的datediff計算?答案是肯定的,你這樣做,因爲在where子句來之前選擇在執行順序看https://stackoverflow.com/questions/24127932/mysql-query-clause-execution-order。您還應該更改隱式聯接和顯式聯接。 –

回答

1

鑑於 DROP TABLE issue_book,return_book;

create table issue_book (book_id int, issue_date date); 
    create table return_book (book_id int, return_date date); 

    insert into issue_book values(1,'2017-01-01'), (2,'2017-09-02'),(3,'2017-09-01'); 
    insert into return_book values(1,'2017-10-08'), (2,'2017-10-08'); 

此查詢

select ib.issue_date,rb.return_date ,datediff(return_date,issue_date) ddiff 
from return_book rb 
join issue_book ib on rb.book_id=ib.book_id 
where datediff(return_date,issue_date)>10; 

結果

+------------+-------------+-------+ 
| issue_date | return_date | ddiff | 
+------------+-------------+-------+ 
| 2017-01-01 | 2017-10-08 | 280 | 
| 2017-09-02 | 2017-10-08 | 36 | 
+------------+-------------+-------+ 
2 rows in set (0.00 sec) 

但也有可能是你的邏輯缺陷,即會發生什麼,如果一本書沒有得到回報 - 將有沒有進入在return_books中。

也不需要一個過程或光標這可以用類似

update return_book rb join issue_book ib on rb.book_id=ib.book_id 
set fine = (datediff(return_date,issue_date) - 10) * 5 
where datediff(return_date,issue_date)>10; 
+0

非常感謝你!是更新會容易得多,但他們已經明確告訴我們在我們學院使用程序,但無論如何,你的答案是真的有幫助..再次感謝! – N97