SQL查询,显示参加过多个活动的运动员的姓名

时间:2014-10-05 08:52:32

标签: mysql sql sql-server

我正在构建一个查询,根据他们参加过多个活动的事实来显示运动员的名字。

为此,我必须使用2个表格,如下所示:

CREATE TABLE ATHLETE(
ATHLETEID CHAR(4),
ATHLETEFIRSTNAME VARCHAR2(20),
ATHLETELASTNAME VARCHAR2(20),
ATHLETEDOB DATE,
REPCOUNTRY VARCHAR2(12),
COACHID CHAR(4),
CONSTRAINT ATHLETE_PK PRIMARY KEY(ATHLETEID),
CONSTRAINT ATHLETE_FK1 FOREIGN KEY(COACHID) REFERENCES COACH(COACHID));

CREATE TABLE RESULTS(
EVENTID CHAR(4),
ATHLETEID CHAR(4),
RANK NUMBER(1),
CONSTRAINT RESULTS_PK PRIMARY KEY(EVENTID,ATHLETEID),
CONSTRAINT RESULTS_FK1 FOREIGN KEY(EVENTID) REFERENCES EVENTSCHEDULE(EVENTID),
CONSTRAINT RESULTS_FK2 FOREIGN KEY(ATHLETEID) REFERENCES ATHLETE(ATHLETEID));

使用下面的查询,我能够显示参与多个事件的ATHLETEID,我正在努力的是显示运动员的名字,因为它在不同的表格中。我很确定我应该使用子查询,但是我不确定如何构建它。

SELECT A.ATHLETEID FROM RESULTS A GROUP BY A.ATHLETEID HAVING COUNT(*) > 1;

提前致谢!

4 个答案:

答案 0 :(得分:2)

只需使用带计数的连接(不需要子查询

SELECT A.ATHLETEID,ATH.ATHLETEFIRSTNAME FROM RESULTS A 
JOIN ATHLETE ATH
ON ATH.ATHLETEID =A.ATHLETEID
GROUP BY A.ATHLETEID,ATH.ATHLETEFIRSTNAME HAVING COUNT(*) > 1;

答案 1 :(得分:2)

除了ShoutCase SQL之外,你需要加入运动员,然后按所有非聚合列进行分组,如下所示(注意我已经将别名切换为与表名对齐):

 SELECT a.ATHLETEID, a.ATHLETEFIRSTNAME, 
        a.ATHLETELASTNAME, COUNT(r.EVENTID) as NumEvents
 FROM RESULTS r
   INNER JOIN ATHLETE a
   ON r.ATHLETEID = a.ATHLETEID 
 GROUP BY a.ATHLETEID, a.ATHLETEFIRSTNAME, a.ATHLETELASTNAME
 HAVING COUNT(r.EVENTID) > 1;

答案 2 :(得分:1)

如果名称是唯一的,您也可以按名称分组,但一般来说,这不是真的,所以子查询很容易:

select A.ATHLETEID, a.ATHLETEFIRSTNAME, ATHLETELASTNAME 
from ATHLETE a 
where 1 < (select count(1) from RESULTS r where r.ATHLETEID = a.ATHLETEID)

答案 3 :(得分:0)

子查询的另一个例子是:

select A.ATHLETEID, a.ATHLETEFIRSTNAME, a.ATHLETELASTNAME 
from ATHLETE a 
where A.ATHLETEID in (SELECT R.ATHLETEID FROM RESULTS R GROUP BY R.ATHLETEID HAVING COUNT(*) > 1)