LeetCode:Database 98.计算布尔表达式的值

Posted Xiao Miao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Database 98.计算布尔表达式的值相关的知识,希望对你有一定的参考价值。

要求:写一个 SQL 查询, 以计算表 Expressions 中的布尔表达式。

表 Variables的结构:

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| name          | varchar |
| value         | int     |
+---------------+---------+
name 是该表主键.
该表包含了存储的变量及其对应的值.

表 Expressions的结构:

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| left_operand  | varchar |
| operator      | enum    |
| right_operand | varchar |
+---------------+---------+
(left_operand, operator, right_operand) 是该表主键.
该表包含了需要计算的布尔表达式.
operator 是枚举类型, 取值于('<', '>', '=')
left_operand 和 right_operand 的值保证存在于 Variables 表单中.

Variables 表:

+------+-------+
| name | value |
+------+-------+
| x    | 66    |
| y    | 77    |
+------+-------+

Expressions 表:

+--------------+----------+---------------+
| left_operand | operator | right_operand |
+--------------+----------+---------------+
| x            | >        | y             |
| x            | <        | y             |
| x            | =        | y             |
| y            | >        | x             |
| y            | <        | x             |
| x            | =        | x             |
+--------------+----------+---------------+

Result Table:

+--------------+----------+---------------+-------+
| left_operand | operator | right_operand | value |
+--------------+----------+---------------+-------+
| x            | >        | y             | false |
| x            | <        | y             | true  |
| x            | =        | y             | false |
| y            | >        | x             | true  |
| y            | <        | x             | false |
| x            | =        | x             | true  |
+--------------+----------+---------------+-------+
如上所示, 你需要通过使用 Variables 表来找到 Expressions 表中的每一个布尔表达式的值.

SQL语句:

with d as(SELECT a.left_operand as l1,b.value as v1,a.operator as o1,a.right_operand as r1,c.value as v2
FROM expressions a
JOIN VARIABLES b
ON b.name=a.left_operand 
JOIN VARIABLES c
ON c.name=a.right_operand)

select l1 as left_operand,o1 as operator,r1 as right_operand,if(o1=o2,'true','false') as value
from(
select l1,o1,r1,
case when v1>v2 then '>'
when v1=v2 then '=' else '<' end as o2
from d)e;

以上是关于LeetCode:Database 98.计算布尔表达式的值的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 178. Rank Scores (Database)

算法leetcode2331. 计算布尔二叉树的值(多语言实现)

算法leetcode2331. 计算布尔二叉树的值(多语言实现)

LeetCode:Database 102.计算税后工资

LeetCode:Database 102.计算税后工资

LeetCode(数据库)- 计算布尔表达式的值