SQL 如何根据来自多行的值 select 行
SQL How to select rows based on values from multiple rows
嗨,我 运行 遇到了与下表有关的问题
CREATE TABLE BOOKS (
Title varchar(255),
Year INT,
Type ENUM("Horror", "Fantasy"),
Pages INT,
PRIMARY KEY (Title, Year)
);
CREATE TABLE AUTHORS(
Title varchar(255),
Year INT,
PlaceOfBirth varchar(255),
AuthorName varchar(255),
PRIMARY KEY (Title, Year, PlaceOfBirth ),
FOREIGN KEY (Title, Year) REFERENCES BOOKS(Title, Year)
);
现在想查询所有只有40页以上恐怖书的作者
SELECT a.AuthorName, b.Pages FROM AUTHORS a INNER JOIN BOOKS b ON a.Title=b.Title AND a.Year=b.Year
WHERE b.Type="Horror" AND b.Pages > 40
现在的问题是,我得到那些写过超过 40 页的恐怖书的作者,但他们也可能有不到 40 页的恐怖书。我想要那些只写 40 页或更长的恐怖书的作者。
如果您想要至少写过一本恐怖书并且所有此类书都超过 40 页的作者姓名,您可以使用 group by
和 having
:
select a.authorname
from authors a
inner join books b on a.title = b.title and a.year = b.year
where b.type = 'Horror'
group by a.authorname
having min(b.pages) > 40
嗨,我 运行 遇到了与下表有关的问题
CREATE TABLE BOOKS (
Title varchar(255),
Year INT,
Type ENUM("Horror", "Fantasy"),
Pages INT,
PRIMARY KEY (Title, Year)
);
CREATE TABLE AUTHORS(
Title varchar(255),
Year INT,
PlaceOfBirth varchar(255),
AuthorName varchar(255),
PRIMARY KEY (Title, Year, PlaceOfBirth ),
FOREIGN KEY (Title, Year) REFERENCES BOOKS(Title, Year)
);
现在想查询所有只有40页以上恐怖书的作者
SELECT a.AuthorName, b.Pages FROM AUTHORS a INNER JOIN BOOKS b ON a.Title=b.Title AND a.Year=b.Year
WHERE b.Type="Horror" AND b.Pages > 40
现在的问题是,我得到那些写过超过 40 页的恐怖书的作者,但他们也可能有不到 40 页的恐怖书。我想要那些只写 40 页或更长的恐怖书的作者。
如果您想要至少写过一本恐怖书并且所有此类书都超过 40 页的作者姓名,您可以使用 group by
和 having
:
select a.authorname
from authors a
inner join books b on a.title = b.title and a.year = b.year
where b.type = 'Horror'
group by a.authorname
having min(b.pages) > 40