我有这些table:
CREATE TABLE students(
id int NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL
);
CREATE TABLE studentsActivities(
studentId int NOT NULL,
activity VARCHAR(30) NOT NULL,
PRIMARY KEY (studentId, activity),
foreign KEY (studentId) REFERENCES students(id)
);
我还得把所有网球或足球的学生的名字都还给我。然而,有一个测试用例我不能通过,它是这样说的:
同名的学生。
我不知道测试用例的具体实现,但我怀疑是这样一种情况:一个叫卡尔的学生打网球,另一个叫卡尔的学生踢足球,卡尔被展示了两次。我怎样才能查询那个数据库得到这样的结果呢?我创建了演示库来尝试:
CREATE TABLE students(
id int NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL
);
CREATE TABLE studentsActivities(
studentId int NOT NULL,
activity VARCHAR(30) NOT NULL,
PRIMARY KEY (studentId, activity),
foreign KEY (studentId) REFERENCES students(id)
);
INSERT INTO students
VALUES
(1, "Jeremy"),
(2, "Hannah"),
(3, "Luke"),
(4, "Frank"),
(5, "Sue"),
(6, "Sue"),
(7, "Peter");
INSERT INTO studentsActivities
VALUES
(1, "Tennis"),
(1, "Football"),
(2, "Running"),
(3, "Tennis"),
(4, "Football"),
(5, "Football"),
(6, "Tennis");
sql fiddle,假设传递集是:
Jeremy
Luke
Frank
Sue
Sue
我尝试过这两个问题,但都没有给出正确答案。
--- 1
SELECT s.name
FROM students s
JOIN studentsActivities sa
ON sa.studentId = s.id
WHERE activity = "Tennis"
UNION
SELECT s.name
FROM students s
JOIN studentsActivities sa
ON sa.studentId = s.id
WHERE activity = "Football"
--- Returns Frank Jeremy Luke Sue (missing one Sue)
--- 2
SELECT s.name
FROM students s
JOIN studentsActivities sa
ON sa.studentId = s.id
WHERE activity = "Tennis"
OR activity = "Football"
ORDER BY s.name;
--- Returns Frank Jeremy Jeremy Luke Sue Sue (too much Jeremies)
2条答案
按热度按时间tct7dpnv1#
联接表,仅筛选包含所需活动的行,并返回不同的行:
请看演示。
结果:
如果您只需要学生的姓名而不需要ID:
请看演示。
结果:
zbwhf8kr2#
你可以用
exists
:db小提琴演示: