SQL - Select 查询 return 只有唯一答案或什么都没有

SQL - Select query to return only a unique answer or nothing

我创建了一个视图来显示数据库中所有书名中包含 'python' 字样的作者。我遇到的问题是,如果有不止一位作者,它就会 return 什么都没有。这是视图的工作代码,我知道我需要使用聚合函数(计数)或使用 EXISTS 实现子查询,但我不确定如何让它工作。

CREATE VIEW sole_python_author(author_first_name, author_last_name)
AS SELECT first_name, last_name
FROM authors, books
WHERE authors.author_id = books.author_id AND
    title LIKE '%Python%'
GROUP BY authors.author_id;

'authors' table:

CREATE TABLE "authors" (
    "author_id" integer NOT NULL,
    "last_name" text,
    "first_name" text,
    Constraint "authors_pkey" Primary Key ("author_id")
);

'books' table:

CREATE TABLE "books" (
    "book_id" integer NOT NULL,
    "title" text NOT NULL,
    "author_id" integer REFERENCES "authors" (author_id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE,
    "subject_id" integer REFERENCES "subjects" (subject_id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE   ,
    Constraint "books_id_pkey" Primary Key ("book_id")  
);

如果只有一位作者写过书名中带有 'python' 的书,则应该 return 他们的名字。如果不止一个,它应该 return 什么都没有。 非常感谢任何帮助!

CREATE VIEW sole_python_author(author_first_name, author_last_name) 
AS 
SELECT first_name, last_name 
FROM authors, books 
WHERE authors.author_id = books.author_id 
AND title LIKE '%Python%'
GROUP BY first_name, last_name
HAVING COUNT(*) = 1

如果没有其他作者,那么只有 return 一行?

我认为这符合您的描述:

SELECT min(a.first_name), min(a.last_name)
FROM authors AS a JOIN books AS b
ON a.author_id = b.author_id 
WHERE b.title LIKE '%Python%'
HAVING COUNT (DISTINCT b.author_id) = 1; 

如果你想要写过名字中有 Python 的书并且没有合著者的作者,那么我认为你需要在书本级别而不是作者级别进行汇总:

CREATE VIEW sole_python_author(author_first_name, author_last_name) AS
    SELECT DISTINCT MAX(first_name), MAX(last_name)
    FROM authors a JOIN
         books b
         ON a.author_id = b.author_id 
    WHERE a.title LIKE '%Python%'
    GROUP BY b.book_id
    HAVING COUNT(*) = 1;

这是有效的,因为 MAX() 只处理一行。

SELECT DISTINCT 是因为一个作者可能写了不止一本这样的书,但你只想要这个名字一次(大概)。注意:这确实假设您正在寻找作者姓名级别而不是 author_id 级别的独特性。

我觉得你的问题模棱两可。这回答了问题:"What authors have been the sole authors of books with "Python" in the title?"