我有表 booksbookType,它们构成 1 X n 关系。

书籍

+-----+------------------+----------+-------+ 
| 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 | 
+-----+------------------+----------+-------+ 

bookTypes

+-----+----------+ 
| id  |   name   | 
+-----+----------+ 
|   1 | Fiction  | 
|   2 | Drama    | 
|   3 | Children | 
+-----+----------+ 

如果所有的书都比例如12(美元)? 在这种情况下,预期的输出将是:

+-----+----------+ 
| id  |   name   | 
+-----+----------+ 
|   1 | Fiction  | 
|   3 | Children | 
+-----+----------+ 

请您参考如下方法:

您可以使用不存在:

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

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

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) 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!