Logical Expressions rules in relational datamodel

前端 未结 1 1274
谎友^
谎友^ 2021-01-16 12:08

I have a logical expression

say c=a+b*d something like

Is it possible to achieve this in a relational datamodel setup? I do not want to hardco

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 13:08

    Such an expression is a tree. Your example, expressed as a tree, is

    =
       c
       +
          a
          *
             b
             d
    

    The leaves of the tree are the primitive symbols a, b, ..., while the roots of the (sub)trees are the operators.

    A simple relational database structure to represent such trees is

    node(id, operator, left_component_id, right_component_id, primitive)
    

    where, in case of a subtree, the operator and the foreign keys for the component nodes will be filled, whereas in case of a primitive, the last attribute will be filled.

    If the arity, i.e. the count of arguments, of your operators is high or even unlimited, the schema will get more complicated. You'll need a separate table

    argument(id, node_id, position, component_id)
    

    that carries the arguments of the referenced node.

    These schemes give you the full power of relational databases. E.g., you can query how many of your expressions have "a" as first argument. On the other hand, a simple expression will get scattered across a lot of database records that way. If you don't need the mechanisms of the database to inspect the inner structure of your expressions, you could just store the entire expression, as a string, in a single record.

    0 讨论(0)
提交回复
热议问题