在条件下寻找主/子表数据库?

时间:2015-05-09 08:26:47

标签: sql sql-server

我有2张桌子:

DECLARE @MASTER TABLE (MAST_ID INT, 
                       MAST_NAME NVARCHAR(10), 
                       IS_ACTIVE CHAR(1)
                      )

INSERT INTO @MASTER 
VALUES (1, 'MAST1', 'A'), (2, 'MAST2', 'I'), 
       (3, 'MAST3', 'A'), (4, 'MAST4', 'A')

SELECT * FROM @MASTER

DECLARE @CHILD TABLE (CHD_ID INT, 
                      MAST_ID INT, 
                      CHD_NAME NVARCHAR(10), 
                      IS_ACTIVE CHAR(1)
                     )

INSERT INTO @CHILD 
VALUES (1, 1, 'CHD1', 'I'), (2, 2, 'CHD2', 'A'), 
       (3, 4, 'CHD3', 'A'), (4, 4, 'CHD4', 'I') 

SELECT * FROM @CHILD
  1. 我需要所有活动的主表数据,这些数据是活动的,对于那些有活动子数据的数据

  2. 我需要所有活跃的孩子以获得以上主数据

  3. 输出应如下所示

    enter image description here

    感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您需要构建一个子查询,以便从MAST_ID表格@CHILD获取IS_ACTIVE = 'A',然后针对@MASTER获取子IS_ACTIVE = 'A'以获取MAST_ID那些SELECT M.* FROM @MASTER M WHERE IS_ACTIVE = 'A' AND MAST_ID IN (SELECT MAST_ID FROM @CHILD C WHERE IS_ACTIVE = 'A')

ArrayList

答案 1 :(得分:0)

select * from @MASTER A where is_active = 'A' and 
exists (select 1 from @child where is_active = 'A' and mast_id = A.mast_id);

select * from @child A where is_active = 'A' and
exists (select 1 from @master where mast_id = A.mast_id and is_active = 'A');

小提琴 - http://sqlfiddle.com/#!6/7a59c/4

答案 2 :(得分:0)

您的问题已得到解答,但对于II部分,您可以使用此查询:

select c.*, m.MAST_NAME
from CHILD c inner join MASTER m
on c.MAST_ID=m.MAST_ID
where m.IS_ACTIVE='A' and c.IS_ACTIVE='A';