查找可用性 = 0 或未知的所有书籍

Find all books where availability is = 0 or unknown

我有一个 table Books,其中有很多 properties。属性存储为键和值。

所以如果书籍是:

1  LOTR
2  Harry Potter 1
3  Harry Potter 2

并且属性是

id  book_id  key        value
1   1        available  0
2   2        available  10
3   2        author     Rowling
4   3        author     Rowling

我希望获得如下结果:

1  LOTR
3  Harry Potter 2

因为图书 id 1 有 0 个可用信息,而 2 有 10 个,而 3 没有任何可用信息。

我知道我可以使用反连接,但我不确定如何使用它。我对反连接有点陌生。

感谢任何帮助。

试试这个:

SELECT b.book_id, a.key, a.value
FROM Books AS B INNER JOIN AnotherTable AS A B.book_id = a.book_id
WHERE a.key = 'available' and (a.value = 0 OR a.value is null)

我不是 100% 确定我理解你的问题,但假设你想要 return properties table 中没有可用性的所有书籍,那么这里是一个选项使用 outer join:

select b.*
from books b
   left join properties p on b.id = p.book_id and p.key = 'available' and p.value > 0
where p.id is null

根据您的数据库,您可能需要 cast join 中的 value 列。

SELECT book_id, title
FROM Books as B
WHERE B.book_id NOT IN (
                SELECT P.book_id 
                FROM properties as P
                WHERE P.key = available AND P.value <> 0)

注意<>表示NOT EQUAL