left连接为null,不等于两者,显示意外结果

6tqwzwtp  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(365)

震惊吧!下面的代码有什么问题?都不是 LEFT JOINNULL 正在选择 Null 行,也不是mysql != 运算符仅显示不匹配的行
两张table
book -书单

id  |   ttl
===========
1   |   Science
2   |   Math
3   |   English

block_book -分配给每个区块的书籍列表

id  |   block|  book
=====================
1   |   1   |   1
2   |   1   |   2

现在,要求显示未分配给块的其余书籍。那我该怎么办

SELECT
    book.id AS id, book.ttl AS book 
FROM
    block_book
JOIN
    book ON book.id != block_book.book
GROUP BY book.id

!= 接线员应该在跟踪结果,不是吗?因为只有主题 English 不在表中 block_book 预期结果

id  |   book
===========
3   |   English

但是所有的书都被选中了。当前结果

id  |   book
===========
1   |   Science
2   |   Math
3   |   English

我试过了 Left JOINNull ```
SELECT
book.id AS id, book.ttl AS book
FROM
block_book
LEFT JOIN
book ON book.id = block_book.book
WHERE block_book.book IS NULL

但它什么也不回
sql小提琴
kx1ctssn

kx1ctssn1#

你应该使用 right join .
所以这应该有效:

SELECT
book.id AS id, book.ttl AS book 
FROM
block_book
RIGHT JOIN
book ON book.id = block_book.book
WHERE block_book.book IS NULL

或者如果你想用 left join ,您应该这样编写查询:

SELECT
book.id AS id, book.ttl AS book 
FROM
book
LEFT JOIN
block_book ON book.id = block_book.book
WHERE block_book.book IS NULL
ewm0tg9j

ewm0tg9j2#

现在,要求显示未分配给块的其余书籍。
最直接的方法是使用 NOT EXISTS :

select b.*
from book b
where not exists (select 1
                  from block_book bb
                  where bb.book = b.id
                 );

相关问题