将SQL中的多个记录与每个布尔值的逻辑OR组合在一起

时间:2018-03-07 10:47:46

标签: mysql

我有下表,其中描述了特定用户对特定对象的权限:

+------+-----------+----------+-----------+------------+------------+
| type | object_id | can_read | can_write | can_delete | can_create |
+------+-----------+----------+-----------+------------+------------+
|    0 |         1 |        1 |         1 |          0 |          1 |
|    0 |         2 |        1 |         0 |          0 |          0 |
|    1 |         1 |        1 |         1 |          1 |          0 |
+------+-----------+----------+-----------+------------+------------+

type和object_id是整数。

type是对象类型。存在共享相同object_id的不同类型的对象,但由于不同的"类型"应该被视为不同的对象。

can_read,can_write,can_delete,can_create是布尔值,它描述当前所选用户可以对(type,object_id)元组执行的操作。

此表是几个UNION的输出,它们既获取单个用户对object_id的权限,又获取特定" Group"的权限。 as object_id,其中单个用户是成员,然后为每个对象类型重复。

现在问题。我现在想要返回与type和object_id不同的行。对于任何重复记录,布尔值应该是逻辑" OR"在每一行。

在这种情况下,上面的示例表应该返回为:

arguments

在这种情况下,由于所选用户具有权限can_read = true,can_write = false,can_delete = false,can_create = true来自单个用户权限,类型= 0,object_id = 1。 然后同一个用户拥有权限can_read = true,can_write = true,can_delete = false,can_create = false来自类型为0的组成员资格,object_id = 1.

因此有效权利是can_read = true,can_write = true,can_delete = false,can_create = true。

2 个答案:

答案 0 :(得分:1)

你可能需要一个聚合函数来合并这种情况下每个类型的最大值的值object_id

   select type, object_id
      , max(can_read) can_read
      , max(can_write) can_write
      , max(can_delete) can_delete
      , max(can_create) can_create
   from my_table 
   group by type, object_id

和联盟

   select type, object_id
      , max(can_read) can_read
      , max(can_write) can_write
      , max(can_delete) can_delete
      , max(can_create) can_create
   from (

    select type, object_id, can_read, can_write, can_delete, can_create
    from table1
    union 

    select type, object_id, can_read, can_write, can_delete, can_create
    from table2
   ) t
   group by type, object_id

答案 1 :(得分:0)

如果1行为1则为1,如果为1则为0,则需要使用MAX()函数:

SELECT type, object_id,
 MAX(can_read),
 MAX(can_write),
 MAX(can_delete),
 MAX(can_create)
FROM myTable
GROUP BY type, object_id