If you know about sakila sample database, then what is the statement to select items currently rented by a user.
If not here is a code explanation:
CREATE TABLE IF NOT EXISTS `rentals` (
`item_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`last_change_date` date NOT NULL,
PRIMARY KEY (`item_id`,`user_id`,`last_change_date`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Notice there is no return date, this is because the last renter has indefinite rental time, until somebody requests this item and it’s transferred to the new renter for indefinite time as well. A user can rent more than one item and there is only one piece of each item so an item_id cannot go to two users at the same time.
I would like to display currently rented items per user_id.
This is a classic sql question. The answer is explained here.
Using
as play-data, to understand the method, look at the output of
The first 3 columns refer to
r1‘s columns, the last 3 refer tor2‘s.As you can see, whenever there is no
r2.last_change_datewhich is greater thanr1.last_change_date, the value is NULL. Those are the rows wherer1.last_change_dateis greatest. So to find the rows you want, you usethe condition