2014-10-26 51 views
2

我试图获得客户,电影和租期逾期的天数(如果租金保持时间超过租期)。如何获取此查询中过期的天数?

由于某些原因,我使用此查询得到的租期过期天数为NULL。

我得到了这个资源表:

http://dev.mysql.com/doc/sakila/en/sakila-structure-tables.html

这里是我的查询:

SELECT first_name, last_name, title, DATEDIFF(DATEDIFF(return_date,rental_date), rental_duration) 
FROM sakila_customer 
JOIN sakila_rental USING (customer_id) 
JOIN sakila_inventory USING (inventory_id) 
JOIN sakila_film USING (film_id) 
WHERE sakila_film.rental_duration < DATEDIFF(sakila_rental.return_date,sakila_rental.rental_date); 
+0

什么都是'date'列的数据类型? – Payam 2014-10-26 23:45:00

+0

类型:日期时间,空值:否,键:MUL,默认值:NULL – 2014-10-27 00:05:51

回答

1

它返回空的原因是因为你对那些音符日期值使用DATEDIFF

看这句话就在这里:

DATEDIFF(DATEDIFF(return_date, rental_date), rental_duration) 

当您执行里面,你会拥有一个整数(回报和租金的日期之间的差异)。 rental_duration也是一个整数,所以当你尝试在它们之间做一个datediff时,你会得到null,因为你没有考虑日期的差异。

因此,您应该做的是获得返还日期和租赁日期,然后从中扣除租赁期限。这个数字会给你逾期日期的数量。

试试这个:

SELECT first_name, last_name, title, (DATEDIFF(return_date, rental_date) - rental_duration) AS daysOverdue 
FROM customer 
JOIN rental USING (customer_id) 
JOIN inventory USING (inventory_id) 
JOIN film USING (film_id) 
WHERE rental_duration < DATEDIFF(return_date, rental_date); 

我从你的链接下载的数据库和MySQL工作台跑这一点,并取得这样的结果集: enter image description here

0

如果有用于计算结果的值都为空,你会得到一个空。

而且,你的表情看起来不正确,请尝试:

Select ... 
datediff(return_date, rental_date) - rental_duration overdue 
from ... 
... 
where datediff(return_date, rental_date) - rental_duration > 0 
+0

当我尝试它说在'where子句'中的未知列'逾期' – 2014-10-26 23:26:39

+0

现在我越来越错误:BIGINT UNSIGNED值超出范围 – 2014-10-26 23:33:14

+0

请提供三个列的样本实际值return_date,rental_date和rental_duration – Bohemian 2014-10-26 23:47:40