sql连接

3zwtqj6y  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(336)

我有这些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)
tct7dpnv

tct7dpnv1#

联接表,仅筛选包含所需活动的行,并返回不同的行:

select distinct s.id, s.name
from students s inner join studentsActivities a
on a.studentId = s.id
where a.activity in ('Tennis', 'Football')

请看演示。
结果:

| id  | name   |
| --- | ------ |
| 1   | Jeremy |
| 3   | Luke   |
| 4   | Frank  |
| 5   | Sue    |
| 6   | Sue    |

如果您只需要学生的姓名而不需要ID:

select s.name
from students s inner join studentsActivities a
on a.studentId = s.id
where a.activity in ('Tennis', 'Football')
group by s.id, s.name

请看演示。
结果:

| name   |
| ------ |
| Jeremy |
| Luke   |
| Frank  |
| Sue    |
| Sue    |
zbwhf8kr

zbwhf8kr2#

你可以用 exists :

select s.*
from students s
where exists (
    select 1 
    from studentsActivities sa 
    where sa.studentId = s.id and sa.activity in ('Tennis', 'Football')
)

db小提琴演示:

id | name  
-: | :-----
 1 | Jeremy
 3 | Luke  
 4 | Frank 
 5 | Sue   
 6 | Sue

相关问题