评估列以使其等于某些内容而不是其他内容?

时间:2018-03-22 03:57:38

标签: mysql

表格:

CREATE TABLE Participation(
ParticipationId INT UNSIGNED AUTO_INCREMENT, 
SwimmerId       INT UNSIGNED NOT NULL,
EventId         INT UNSIGNED NOT NULL,
Committed       BOOLEAN,
CommitTime      DATETIME,
Participated    BOOLEAN,
Result          VARCHAR(100),
Comment         VARCHAR(100),
CommentCoachId  INT UNSIGNED,
CONSTRAINT participation_pk PRIMARY KEY(ParticipationId),
CONSTRAINT participation_ck_1 UNIQUE(SwimmerId, EventId),
CONSTRAINT participation_swimmer_fk FOREIGN KEY(SwimmerId) 
    REFERENCES Swimmer(SwimmerId),
CONSTRAINT participation_event_fk FOREIGN KEY(EventId) 
    REFERENCES Event(EventId),
CONSTRAINT participation_coach_fk FOREIGN KEY(CommentCoachId) 
    REFERENCES Coach(CoachId)
);

CREATE TABLE Swimmer(
SwimmerId       INT UNSIGNED AUTO_INCREMENT, 
LName           VARCHAR(30) NOT NULL,
FName           VARCHAR(30) NOT NULL,
Phone           VARCHAR(12) NOT NULL,
EMail           VARCHAR(60) NOT NULL,
JoinTime        DATE NOT NULL,
CurrentLevelId  INT UNSIGNED NOT NULL,
Main_CT_Id      INT UNSIGNED NOT NULL,
Main_CT_Since   DATE NOT NULL,
CONSTRAINT swimmer_pk PRIMARY KEY(SwimmerId),
CONSTRAINT swimmer_level_fk FOREIGN KEY(CurrentLevelId) 
    REFERENCES Level(LevelId),
CONSTRAINT swimmer_caretaker_fk FOREIGN KEY(Main_CT_Id) 
    REFERENCES Caretaker(CT_Id)
);

CREATE TABLE Event(
EventId      INT UNSIGNED AUTO_INCREMENT, 
Title        VARCHAR(100) NOT NULL,
StartTime    TIME NOT NULL,
EndTime      TIME NOT NULL,
MeetId       INT UNSIGNED NOT NULL,
LevelId      INT UNSIGNED NOT NULL,
CONSTRAINT event_pk PRIMARY KEY(EventId),
CONSTRAINT event_meet_fk FOREIGN KEY(MeetId) 
    REFERENCES Meet(MeetId),
CONSTRAINT event_level_fk FOREIGN KEY(LevelId) 
    REFERENCES Level(LevelId)
);

有3张桌子,我想列出参加比赛3但不参加比赛4的游泳运动员的名字。

首先我尝试了这个:SELECT s.FName AS "fname", s.LName AS "lname" FROM Swimmer s, Participation p, Event e WHERE s.SwimmerId = p.SwimmerId AND e.EventId = p.EventId AND p.EventId = 3 AND p.EventId != 4;

我现在已经在网上搜索了一段时间,但是还没有能够找到这样的东西。

这是我找到解决方案的最接近的地方:Where clause for equals a field, not equal another但我不确定我的" wp_posts.id"和" wp_term_relationships"会在我的情况下。

2 个答案:

答案 0 :(得分:0)

你可以试试这个,交配:

SELECT s.FName AS 'fname', s.LName AS 'lname'
FROM swimmer s
    INNER JOIN participation p ON p.SwimmerId = s.SwimmerId
    -- swimmer(s) that did not participate in event 4
    INNER JOIN participation p4  ON p4.SwimmerID = s.SwimmerId
        AND p4.EventId != 4
WHERE p.EventId = 3;

答案 1 :(得分:0)

这是我作为解决方案得到的:

SELECT s.FName AS "fname", s.LName AS "lname" FROM Swimmer s
WHERE s.SwimmerId IN (
   SELECT DISTINCT p.SwimmerId FROM Participation p WHERE p.EventId = 3
) AND s.SwimmerId NOT IN (
   SELECT DISTINCT p.SwimmerId FROM Participation p WHERE p.EventId = 4
);