SQL从1 x N中选择所有大于

j.D*_*Doe 2 mysql sql mariadb

我有桌子booksbookType它们构成1 X n关系。

books

+-----+------------------+----------+-------+
| id  |      title       | bookType | price |
+-----+------------------+----------+-------+
|   1 | Wizard of Oz     |        3 |    14 |
|   2 | Huckleberry Finn |        1 |    16 |
|   3 | Harry Potter     |        2 |    25 |
|   4 | Moby Dick        |        2 |    11 |
+-----+------------------+----------+-------+
Run Code Online (Sandbox Code Playgroud)

bookTypes

+-----+----------+
| id  |   name   |
+-----+----------+
|   1 | Fiction  |
|   2 | Drama    |
|   3 | Children |
+-----+----------+
Run Code Online (Sandbox Code Playgroud)

如果所有书籍的价格都比12($)高,我该如何检索bookTypes?在这种情况下,预期输出为:

+-----+----------+
| id  |   name   |
+-----+----------+
|   1 | Fiction  |
|   3 | Children |
+-----+----------+
Run Code Online (Sandbox Code Playgroud)

GMB*_*GMB 5

您可以使用not exists

select t.*
from bookTypes t
where not exists (
    select 1
    from books b
    where b.bookType = t.id and b.price < 12
)
Run Code Online (Sandbox Code Playgroud)

如果要选择至少具有一本关联书的书类型:

select t.*
from bookTypes t
where 
    exists (select 1 from books b where b.bookType = t.id)
    and not exists (select 1 from books b where b.bookType = t.id and b.price < 12)
Run Code Online (Sandbox Code Playgroud)