简体   繁体   English

Select 行,以便其中两列分别唯一

[英]Select rows so that two of the columns are separately unique

Table user_book describes every user's favorite books.user_book描述了每个用户最喜欢的书籍。

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.我想编写一个查询(可能是一个定义多个语句的with子句 - 但不是一个过程),它会尝试将一本最喜欢的书分发给拥有一本或多本最喜欢的书的每个用户。

Any ideas how to do it?任何想法如何做到这一点?

More details:更多细节:

The distribution plan may be naive.分配计划可能是幼稚的。 ie 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).这意味着有时某些书籍可能无法分发,和/或有时某些用户可能无法获得任何书籍(示例 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).一本书不能分发给两个不同的用户(示例 3)。

Examples:例子:

1. A possible distribution: 1. 一种可能的分布:

(1, 1)
(2, 2)
(3, 5)

2. A possible distribution (here user 3 got nothing, and book 1 was not distributed. That's acceptable): 2. 一种可能的分发方式(这里用户 3 什么都没有,并且书籍 1 没有分发。这是可以接受的):

(1, 2)
(2, 5)

3. An impossible distribution (both users 1 and 2 got book 2, that's not allowed): 3. 不可能的分发(用户 1 和 2 都拿到了书 2,这是不允许的):

(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 中的一个字段上没有重复的 select 记录?

SQL: How do I SELECT only the rows with a unique value on certain column? SQL:我如何 SELECT 仅在特定列上具有唯一值的行?

How to select unique records by SQL 如何通过 SQL 获得 select 唯一记录

The user_book table should also have a UNIQUE(user_id, book_id) constraint. user_book 表还应该有一个UNIQUE(user_id, book_id)约束。

A simple solution like this returns a list in which each user gets zero or one book and each book is given to zero or one user:像这样一个简单的解决方案返回一个列表,其中每个用户获得零或一本书,每本书被分配给零或一个用户:

WITH list AS (SELECT user_id, MIN(book_id) AS fav_book FROM user_book GROUP BY user_id)
SELECT fav_book, MIN(user_id) FROM list GROUP BY fav_book

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM