【问题标题】:Can I make a integer field with bit information and use index?我可以使用位信息创建一个整数字段并使用索引吗?
【发布时间】:2017-03-25 01:41:52
【问题描述】:

我正在尝试解决一个难题more info。所以我有用这些碎片创建的碎片和解决方案。

 Pieces: piece_id
 Solution: solution_id

如果我有三块将有 8 个解决方案2^3。我的想法是使用solution_id 来指明其中的部分。

 solution_id   pieces 
      0          000  -- no pieces (not really a solution)
      1          001  -- only the piece_id = 1
      2          010  -- only the piece_id = 2
      3          011  -- have piece 1 and 2
      4          100
      5          101
      6          110
      7          111  -- all pieces (not really a solution because need solve two parts) 

我需要两个解决方案,但 solution2 无法在 solution1 上找到任何内容

问题是:

  • 我能否在整数之间进行按位运算,以了解两个解决方案是否共享任何部分或需要位数组?
  • 我可以使用一个索引来提高此联接的性能吗?
  • 有更好的方法吗?

    SELECT s1.solution_id, s2.solution_id
    FROM solutions
    WHERE s1.solution_id & s2.solution_id = 0
    

【问题讨论】:

    标签: sql postgresql bitwise-operators


    【解决方案1】:

    您似乎知道问题的答案:

    1. 是的,您可以使用按位运算。
    2. 您可能无法使用索引来优化此查询。

    但是,您可以以不同的方式存储数据。更好的数据结构是:

    solution_id    piece
       1             1
       2             2
       3             1
       3             2
    . . .
    

    然后您可以使用连接和更传统的数据库操作。

    【讨论】:

    • 是的,我想知道对于这种情况,位数组是否是更好的选择。我已经有了这个结构。存放碎片是好的。但是要找到哪对解决方案没有相同的部分是非常复杂的。也许你可以看看这个演示。 rextester.com/GGGUTW70272
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多