我有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
我需要所有活动的主表数据,这些数据是活动的,对于那些有活动子数据的数据
我需要所有活跃的孩子以获得以上主数据
输出应如下所示
感谢您的帮助。
答案 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');
答案 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';