Table user_book
describes every user's favorite books.
CREATE TABLE user_book (
user_id INT,
book_id INT,
FOREIGN KEY (user_id) REFERENCES user(id),
FOREIGN KEY (book_id) REFERENCES book(id)
);
insert into user_book (user_id, book_id) values
(1, 1),
(1, 2),
(1, 5),
(2, 2),
(2, 5),
(3, 2),
(3, 5);
I want to write a query (possibly a with
clause that defines multiple statements ― but not a procedure) that would try to distribute ONE favorite book to every user who has one or more favorite books.
Any ideas how to do it?
More details:
The distribution plan may be naive. i.e. it may look as if you went user after user and each time randomly gave the user whatever favorite book was still available if there was any, without considering what would be left for the remaining users.
This means that sometimes some books may not be distributed, and/or sometimes some users may not get any book (example 2). This can happen when the numbers of books and users are not equal, and/or due to the specific distribution order that you have used.
A book cannot be distributed to two different users (example 3).
Examples:
1. A possible distribution:
(1, 1)
(2, 2)
(3, 5)
2. A possible distribution (here user 3 got nothing, and book 1 was not distributed. That's acceptable):
(1, 2)
(2, 5)
3. An impossible distribution (both users 1 and 2 got book 2, that's not allowed):
(1, 2)
(2, 2)
(3, 5)
Similar questions that are not exactly this one:
How to select records without duplicate on just one field in SQL?
SQL: How do I SELECT only the rows with a unique value on certain column?