1

可能重复:
sql 查询将两列与一列连接

所以我在 MySQL 中获取查询时遇到了一些麻烦。

这是我现在使用的表

DROP TABLE IF EXISTS `qualifications`;
CREATE TABLE `qualifications`(
    `activity` int NOT NULL,
    `group` int NOT NULL,
`tournament` int NOT NULL,
`judge_1` int NOT NULL,
`grade_1` int NOT NULL,
`judge_2` int NOT NULL,
`grade_2` int NOT NULL,
`judge_3` int NOT NULL,
`grade_3` int NOT NULL,
PRIMARY KEY(`activity`,`group`),
FOREIGN KEY(`activity`) REFERENCES `activities`(`id`),
FOREIGN KEY(`group`) REFERENCES `groups`(`id`),
FOREIGN KEY(`judge_1`) REFERENCES `judges`(`id`),
FOREIGN KEY(`judge_2`) REFERENCES `judges`(`id`),
FOREIGN KEY(`judge_3`) REFERENCES `judges`(`id`),
FOREIGN KEY(`tournament`) REFERENCES `tournaments`(`id`)
)ENGINE=InnoDB, DEFAULT CHARSET=utf8;

我想要的是获得活动名称、组名、锦标赛名称以及所有 3 名评委的姓名和成绩。这是我到目前为止的查询:

select a.name as Game, t.name as Tornament, g.name as "Group", j.name as Judge1, j.name as Judge2, (q.grade_1+q.grade_2+q.grade_3) as Grades from activities a, groups g, judges j, tournaments t, qualifications c where
a.id = q.activity and t.id = q.tournament and g.id = q.group and g.id = 2;

当然,除了法官姓名之外,这很好用……我怎样才能在一个结果中获得 3 个法官姓名?

提前谢谢大家,如果我不能很好地解释自己,很抱歉。

4

2 回答 2

0

Judges假设名称存在,加入表以获取名称。

    select a.name as Game, t.name as Tornament, g.name as "Group",
          j1.name as Judge1, 
          j2.name as Judge2,
          j3.name as Judge3,
          (q.grade_1+q.grade_2+q.grade_3) as Grades 
    from activities a JOIN judges j1
         ON a.judge_1 = j1.id
         JOIN judges j2
         ON a.judge_2 = j2.id
         JOIN judges j3
         ON a.judge_3 = j3.id
         JOIN qualifications q 
         ON a.id = q.activity 
         JOIN tournaments t
         ON t.id = q.tournament 
         JOIN groups g
         ON g.id = q.group 
     WHERE g.id = 2;
于 2012-11-09T06:41:52.700 回答
0

作为@Yogendra Singh 的答案的替代方案,并且如果您可以容忍将名称连接成分隔字符串(您可以将其用作分隔符,例如U+001e),您可以judges通过将结果与列GROUP_CONCAT()的聚合judges.name

SELECT   a.name                              AS Game,
         t.name                              AS Tournament,
         g.name                              AS Group,
         GROUP_CONCAT(j.name SEPARATOR 0x1e) AS Judges,
         q.grade_1 + q.grade_2 + q.grade_3   AS Grades 
FROM     activities     a
    JOIN judges         j ON j.id IN (a.judge_1, a.judge_2, a.judge_3)
    JOIN qualifications q ON a.id = q.activity 
    JOIN tournaments    t ON t.id = q.tournament 
    JOIN groups         g ON g.id = q.group 
WHERE    g.id = 2
GROUP BY a.id, t.id
于 2012-11-09T06:48:47.317 回答