【问题标题】:Find all books where availability is = 0 or unknown查找可用性为 = 0 或未知的所有书籍
【发布时间】:2016-10-29 20:27:56
【问题描述】:

我有一张桌子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

因为 Book id 1 的可用性为 0,2 的可用性为 10,而 3 没有任何可用性信息。

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

感谢任何帮助。

【问题讨论】:

  • 为什么不返回Harry Potter 1?不了解您的预期结果...
  • @sgeddes,似乎 1 用作卷,而不是可用性。
  • @sgeddes 我使用Harry Potter 1 作为第一本书的名称。另外,我所追求的是所有书籍,我知道它们都被拿走了,或者我不确定它们的可用性。 (这是一个图书馆管理门户)

标签: sql join anti-join


【解决方案1】:

我不是 100% 确定我理解您的问题,但假设您想要退回所有在 properties 表中没有可用的书籍,那么这里有一个使用 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 列。

【讨论】:

  • @cableload 我正在寻找可用性为 0 或“null”的书籍
  • @Amit,是的,p.id is null 的 where 部分将处理 null 部分
  • @cableload -- 这就是这样做的。它将返回 null 结果以及任何值不 > 0 的结果,因此将返回 0...
【解决方案2】:

试试这个:

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)

【讨论】:

    【解决方案3】:
    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)
    

    注意&lt;&gt; 表示NOT EQUAL

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      相关资源
      最近更新 更多