我已经搜索过,但似乎无法找到我是如何做到这一点的。基本上我有两个表,如果这个稍微复杂一点,简单的连接就可以了。
我想要达到的目标是每个学生选择两个科目,并且每周为每个科目分数一定数量的分数。然后我希望能够显示学生的名字,他的科目1,然后是分数,然后是科目2和分数。通过下面的查询,这显然适用于显示主题1中的分数,但我对如何获得主题2感到困惑。
$query = "SELECT pupils.name, pupils.subject1, pupils.subject2, subjects.week1 + week2 + week3 AS subject1points
FROM pupils, subjects
WHERE pupils.subject1 = subjects.subject";
$result = @mysql_query ($query);
if ($result) {
echo....
也许是某种子查询?提前致谢。当然,我正在完成桌面并显示结果。
答案 0 :(得分:1)
您可以加入subjects
三次,但您需要使用别名来消除列的歧义:
SELECT
pupils.name,
pupils.subject1,
pupils.subject2,
pupils.subject3,
s1.week1 + s1.week2 + s1.week3 AS subject1points,
s2.week1 + s2.week2 + s2.week3 AS subject2points,
s3.week1 + s3.week2 + s3.week3 AS subject3points
FROM
pupils, subjects s1, subjects s2, subjects s3
WHERE
pupils.subject1 = s1.subject
AND
pupils.subject2 = s2.subject
AND
pupils.subject3 = s3.subject
在上面的查询中,s1
,s2
和s3
是别名。定义后,您可以在通常使用完整表名的任何地方使用它们。
另一种方式,也就是我个人的偏好,是使用JOIN
语法:
SELECT
p.name,
p.subject1,
p.subject2,
p.subject3,
s1.week1 + s1.week2 + s1.week3 AS subject1points,
s2.week1 + s2.week2 + s2.week3 AS subject2points,
s3.week1 + s3.week2 + s3.week3 AS subject3points
FROM
pupils p
JOIN
subjects s1 ON p.subject1 = s1.subject
JOIN
subjects s2 ON p.subject2 = s2.subject
JOIN
subjects s3 ON p.subject3 = s3.subject
在上面的查询中,我还将pupils
别名为p
。我更喜欢这种语法,因为它非常清楚。如果任何学生的科目可以为空(subject1
,subject2
或subject3
),那么您可能需要将这些更改为LEFT JOIN
以便您仍然可以查看任何非空科目的结果。
答案 1 :(得分:0)
使用三个连接。我想这就是你想要的:
SELECT p.name, p.subject1, (s1.week1 + s1.week2 + s1.week3) as score1,
p.subject2, (s2.week1 + s2.week2 + s2.week3) as score2,
p.subject3, (s3.week1 + s3.week2 + s3.week3) as score3
FROM pupils p LEFT JOIN
subjects s1
ON p.subject1 = s1.subject LEFT JOIN
subjects s2
ON p.subject2 = s2.subject LEFT JOIN
subjects s3
ON p.subject3 = s3.subject;
请注意,您应该学习使用正确的显式join
语法,尤其是在您相对较新的SQL时。现在是开始养成良好习惯的时候了。
答案 2 :(得分:0)
我会查询加入一张有两份主题表的学生表。
修改强>
我不打扰我所表达的想法,因为其他人已经这样做了。但是,只有2个科目,而不是3个(分数为3周),但这只是意味着离开s3
。