0

我有以下架构和相关数据。

-- Schema
CREATE TABLE [PERSON] (
    [id] int NOT NULL,
    [first_name] varchar(50) NOT NULL,
    [last_name] varchar (50) NOT NULL
    CONSTRAINT [PK__PERSON] PRIMARY KEY ([id])
) 
GO

CREATE TABLE [EVENT] (
    [id] int NOT NULL,
    [name] varchar(50) NOT NULL
    CONSTRAINT [PK__EVENT] PRIMARY KEY ([id])
)
GO

CREATE TABLE [EVENT_PARTICIPANT] (
    [event_id] int NOT NULL,
    [person_id] int NOT NULL
    CONSTRAINT [PK__EVENT_PARTICIPANT] PRIMARY KEY ([event_id], [person_id])
)
GO

ALTER TABLE [EVENT_PARTICIPANT] ADD CONSTRAINT [FK__EVENT__EVENT_PARTICIPANT__event_id]
    FOREIGN KEY ([event_id])
    REFERENCES [EVENT]([id])
GO

ALTER TABLE [EVENT_PARTICIPANT] ADD CONSTRAINT [FK__PERSON__EVENT_PARTICIPANT__person_id]
    FOREIGN KEY ([person_id])
    REFERENCES [PERSON]([id])
GO

-- data
INSERT INTO [PERSON] VALUES(1, 'Alpha', 'A')
INSERT INTO [PERSON] VALUES(2, 'Bravo', 'B')
INSERT INTO [PERSON] VALUES(3, 'Charlie', 'C')
INSERT INTO [PERSON] VALUES(4, 'Delta', 'D')
INSERT INTO [PERSON] VALUES(5, 'Echo', 'E')
INSERT INTO [PERSON] VALUES(6, 'Foxtrot', 'F')
INSERT INTO [PERSON] VALUES(7, 'Golf', 'G')
INSERT INTO [PERSON] VALUES(8, 'Hotel', 'H')
INSERT INTO [PERSON] VALUES(9, 'India', 'I')
INSERT INTO [PERSON] VALUES(10, 'Juliet', 'J')
GO

INSERT INTO [EVENT] VALUES(1, 'Event A')
INSERT INTO [EVENT] VALUES(2, 'Event B')
INSERT INTO [EVENT] VALUES(3, 'Event C')
INSERT INTO [EVENT] VALUES(4, 'Event D')
INSERT INTO [EVENT] VALUES(5, 'Event E')
INSERT INTO [EVENT] VALUES(6, 'Event F')
INSERT INTO [EVENT] VALUES(7, 'Event G')
INSERT INTO [EVENT] VALUES(8, 'Event H')
INSERT INTO [EVENT] VALUES(9, 'Event I')
INSERT INTO [EVENT] VALUES(10, 'Event J')
GO

INSERT INTO [EVENT_PARTICIPANT] VALUES(1,1)
INSERT INTO [EVENT_PARTICIPANT] VALUES(1,2)
INSERT INTO [EVENT_PARTICIPANT] VALUES(1,3)
INSERT INTO [EVENT_PARTICIPANT] VALUES(2,4)
INSERT INTO [EVENT_PARTICIPANT] VALUES(2,5)
INSERT INTO [EVENT_PARTICIPANT] VALUES(2,6)
INSERT INTO [EVENT_PARTICIPANT] VALUES(3,5)
INSERT INTO [EVENT_PARTICIPANT] VALUES(3,6)
INSERT INTO [EVENT_PARTICIPANT] VALUES(4,1)
INSERT INTO [EVENT_PARTICIPANT] VALUES(4,4)
INSERT INTO [EVENT_PARTICIPANT] VALUES(5,1)
INSERT INTO [EVENT_PARTICIPANT] VALUES(6,7)
INSERT INTO [EVENT_PARTICIPANT] VALUES(7,8)
INSERT INTO [EVENT_PARTICIPANT] VALUES(8,9)
GO

我需要找到所有有匹配参与者的冲突事件,以便查询为每个事件返回与其冲突的事件列表。匹配不一定是 100% 即使一个人匹配,也意味着事件相互冲突。

我已经为每个事件生成了一个以逗号分隔的事件参与者列表,但是在如何编写一个有效的查询来获取 SQL Server 2008 的冲突事件时遇到了一些困难。

谢谢!

4

1 回答 1

0

您可以尝试使用此查询:

select distinct ep1.event_id,ep2.event_id from EVENT_PARTICIPANT ep1 inner join EVENT_PARTICIPANT ep2 on ep1.person_id=ep2.person_id where ep1.event_id <> ep2.event_id order by 1,2

于 2012-12-22T07:36:56.787 回答