SQL - 选择查询以仅返回唯一答案或不返回任何内容

时间:2016-04-09 13:54:49

标签: sql postgresql subquery

我创建了一个视图,以显示撰写数据库中所有书籍的作者,其中包含' python'在标题中。我遇到的问题是,如果有多位作者,则不会返回任何内容。这是视图的工作代码,我知道我需要使用聚合函数(count)实现子查询或使用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;

作者'表:

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

'书籍'表:

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")  
);

如果只有一位作者用“蟒蛇”编写了一本书。在标题中,它应该返回他们的名字。如果有多个,它应该什么都不返回。 非常感谢任何帮助!

3 个答案:

答案 0 :(得分:1)

如果没有其他作者,那么只返回一行吗?

我认为这符合您的描述:

<?php

//Set The Database Name, No Other Editing Of This File Should Be Done
 define("sqliteDatabase", "PlayerVsPlayerDatabase" );

 //Nothing Below Needs Touched
 date_default_timezone_set('UTC');

 if(!file_exists("${sqliteDatabase}.sqlite3")) {

    try {

        // Create (connect to) SQLite database in file
        $file_db = new PDO("sqlite:${sqliteDatabase}.sqlite3");

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果您希望在名称中使用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级别上寻找清晰度。

我发现你的问题含糊不清。这回答了这个问题:“作者是标题中”Python“书籍的唯一作者?”