除了查询之外有问题

时间:2015-10-05 13:59:35

标签: mysql

我有两张桌子(书籍和借来的)。

我想从表Books中选择所有内容。 但首先它将检查表BookID中是否存在Borrowed,如果它确实存在且Status = 1,则它将不会包含在select *语句中。

我试过这个但是没有用

select * from Books
except
select `BookdID` where `Status`=1

请帮帮我。这是我的表

书籍:

 | BookID     | Title       | Author       |
 |:-----------|------------:|:------------:|
 | 1          | The Stars   | William Evan |   
 | 2          | Science 3   | Vhong Navaro |
 | 3          | Let It Burn | Jun Ryl      |
 | 4          | Sky Below   | Jason Midfle |
 | 5          | Wish It     | Shan Uddle   |

借来:

 | BookID     | BorrowerID  | Status       |
 |:-----------|------------:|:------------:|
 | 6          | 12          | 0            |   
 | 5          | 4           | 0            |
 | 2          | 3           | 1            |
 | 18         | 6           | 1            |
 | 5          | 3           | 0            |

我的目标输出:

| BookID     | Title       | Author       |
|:-----------|------------:|:------------:|
| 1          | The Stars   | William Evan |   
| 3          | Let It Burn | Jun Ryl      |
| 4          | Sky Below   | Jason Midfle |
| 5          | Wish It     | Shan Uddle   |
  *(BookID 2 is is not shown because in the table `Borrowed`, BookID 2's `Status` = 1)*

1 个答案:

答案 0 :(得分:3)

select b1.* 
from Books b1
left join Borrowed b2 on b1.bookid = b2.bookid
                     and b2.`Status` = 1
where b2.bookid is null

请参阅this great explanation of joins