我有以下数据的两个表:
Test_parent
:
parent_id title
------------------
1 Parent1
2 Parent2
3 Parent3
4 Parent4
Test_child
:
child_id parent_id property
------------------------------------
1 1 A
2 2 A
3 2 B
4 3 A
5 3 C
6 4 A
我想选择表test_parent所有行父包含儿童(两者)特性A和B(所以这将是创纪录的PARENT_ID = 2)
这是我写到目前为止最好的解决办法:
select *
from test_parent p
where (select COUNT(property)
from test_child c
where p.parent_id = c.parent_id and c.property in ('A', 'B')) = 2
有没有更“正确”的方式?
非常感谢!
这是对象的完全脚本:
CREATE TABLE [dbo].[test_parent](
[parent_id] [int] IDENTITY(1,1) NOT NULL,
[title] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_test_parent] PRIMARY KEY CLUSTERED
([parent_id]))
GO
CREATE TABLE [dbo].[test_child](
[child_id] [int] IDENTITY(1,1) NOT NULL,
[parent_id] [int] NOT NULL,
[property] [nvarchar](10) NOT NULL,
CONSTRAINT [PK_test_child] PRIMARY KEY CLUSTERED
([child_id]))
GO
ALTER TABLE [dbo].[test_child] WITH CHECK ADD CONSTRAINT [FK_test_child_test_child] FOREIGN KEY([parent_id])
REFERENCES [dbo].[test_parent] ([parent_id])
GO
ALTER TABLE [dbo].[test_child] CHECK CONSTRAINT [FK_test_child_test_child]
GO
SET IDENTITY_INSERT [dbo].[test_parent] ON;
INSERT INTO [dbo].[test_parent]([parent_id], [title])
SELECT 1, N'Parent1' UNION ALL
SELECT 2, N'Parent2' UNION ALL
SELECT 3, N'Parent3' UNION ALL
SELECT 4, N'Parent4'
SET IDENTITY_INSERT [dbo].[test_parent] OFF;
GO
SET IDENTITY_INSERT [dbo].[test_child] ON;
INSERT INTO [dbo].[test_child]([child_id], [parent_id], [property])
SELECT 1, 1, N'A' UNION ALL
SELECT 2, 2, N'A' UNION ALL
SELECT 3, 2, N'B' UNION ALL
SELECT 4, 3, N'A' UNION ALL
SELECT 5, 3, N'C' UNION ALL
SELECT 6, 4, N'A'
GO
SET IDENTITY_INSERT [dbo].[test_child] OFF;