选择不同情况下的所有内容

时间:2019-01-28 11:39:42

标签: mysql sql oracle

我想基于活动列

的值从表中选择所有内容
  1. 如果active = 1,则选择*
  2. 如果active = 0,则不选择任何内容
  3. 如果active为null,则根据parentNode的活动进行选择

该表如下所示:

  mytable:
 node | parentNode | active | moreColumns

我写的是

select *
from mytable
where active = case
           when active = 1 then 1
    case
           when active is null then (select node.active 
                                     from mytable 
                                     where parentNode = node) end;  

该查询无法正常工作。有什么建议吗?

3 个答案:

答案 0 :(得分:2)

您处在正确的轨道上。对于关联的子查询,您需要使用表别名和合格的列名-所有查询中的好主意:

select t.*
from mytable t
where t.active = 1 or
      (t.active is null and
       (select t2.active
        from mytable t2
        where t2.node = t.parentnode
       ) = 1
      )

答案 1 :(得分:1)

select * from mytable where 
    1 = case 
            when active = 1 then 1
            when active = 0 then 0
            when nvl(active,-1)=-1 then 
                case 
                    when parentNode = Node then 1
                    else 0
                end
        end;

答案 2 :(得分:0)

在Oracle中,您可以使用分层查询来查找活动状态为非null的最新祖先(这将向上浏览多个祖先级别,而不仅仅是查看父级):

Oracle设置

CREATE TABLE mytable ( node, parentNode, active ) AS
  SELECT 1, null, 0    FROM DUAL UNION ALL
  SELECT 2, 1,    1    FROM DUAL UNION ALL
  SELECT 3, 2,    null FROM DUAL UNION ALL
  SELECT 4, 3,    null FROM DUAL UNION ALL
  SELECT 5, 1,    0    FROM DUAL UNION ALL
  SELECT 6, 5,    null FROM DUAL UNION ALL
  SELECT 7, 6,    null FROM DUAL UNION ALL
  SELECT 8, null, null FROM DUAL;

查询

SELECT *
FROM   (
  SELECT CONNECT_BY_ROOT( node ) AS node,
         CONNECT_BY_ROOT( parentNode ) AS parentNode,
         active
  FROM   mytable
  WHERE  CONNECT_BY_ISLEAF = 1
  CONNECT BY PRIOR parentNode = node
         AND PRIOR active IS NULL
)
WHERE  active = 1;

输出

NODE | PARENTNODE | ACTIVE
---: | ---------: | -----:
   2 |          1 |      1
   3 |          2 |      1
   4 |          3 |      1

db <>提琴here