2

好的,所以我有一个图书馆风格的数据库,我想获取所有已售罄的书籍的名称。如果所有副本都已出租,则该书被视为已售罄。到目前为止我的查询是:

SELECT Book.Title, Physical_book.book_available AS Available
FROM Book
JOIN Physical_book ON Book.book_id = Physical_Book.book_id
WHERE Physical_book.book_available = 'n';

我的 Physical_Media 表具有 book_available 属性,它告诉您该书是否可用 N 或 Y。在此表中,如果有多个副本,则重复书籍。意思是,如果这本书是,Title One那么我为Title One All 有三个二,并且 Book_ID 相同2。在这三本书中,有两本标有n,另一本标有y。从技术上讲,我想要的是,这个查询只提取那些所有书籍都售罄的人。由于它返回的结果Title ONe显然不能正常工作。有任何想法吗?

表格示例

/* Physical_Book Table */
INSERT INTO Physical_Book (Physical_ID, Book_ID, Book_available)
VALUES (1,1,'y');
INSERT INTO Physical_Book (Physical_ID, Book_ID, Book_available)
VALUES (2,1,'n');
INSERT INTO Physical_Book (Physical_ID, Book_ID, Book_available)
VALUES (3,1,'n');

/*Book Table*/
INSERT INTO Book (Book_ID, author_id, genre_id, title, copyright)
VALUES (1, Tammy, Horror, Book One, 1999)

使用 JW 查询

SELECT Book.Title, Physical_book.book_available AS Available
FROM Book
JOIN Physical_book ON Book.book_id = Physical_Book.book_id
Group BY Book.title, Physical_book.book_available
HAVING COUNT (*) = COUNT (CASE WHEN book_available = 'n' THEN 1 END);
4

2 回答 2

2
SELECT  ID, title
FROM    Physical_Book
GROUP   BY ID, title
HAVING  COUNT(*) = COUNT(CASE WHEN book_available = 'n' THEN 1 END)

假设你有这些记录,

╔════╦═══════════╦════════════════╗
║ ID ║   TITLE   ║ BOOK_AVAILABLE ║
╠════╬═══════════╬════════════════╣
║  1 ║ Title One ║ y              ║
║  1 ║ Title One ║ n              ║
║  1 ║ Title One ║ n              ║
║  2 ║ Title Two ║ n              ║
║  2 ║ Title Two ║ n              ║
╚════╩═══════════╩════════════════╝

查询的预期输出是

╔════╦═══════════╗
║ ID ║   TITLE   ║
╠════╬═══════════╣
║  2 ║ Title Two ║
╚════╩═══════════╝
于 2013-04-22T02:43:05.720 回答
0

像这样的东西应该工作。

select title
from book
where not exists
(select title
from book
where available = 'Y'
)
于 2013-04-22T02:42:27.527 回答