Mysql 选择最大状态ID
我有这样的桌子: 地位Mysql 选择最大状态ID,mysql,sql,select,group-by,greatest-n-per-group,Mysql,Sql,Select,Group By,Greatest N Per Group,我有这样的桌子: 地位 StatusID | Status | ------------------- 1 | Good | 2 | Nice | 3 | Bad | 课程 CourseID | Course | ------------------- 1 | Math | 2 | Science| 3 | Art | 过程 StudentID| CourseID | Status I
StatusID | Status |
-------------------
1 | Good |
2 | Nice |
3 | Bad |
课程
CourseID | Course |
-------------------
1 | Math |
2 | Science|
3 | Art |
过程
StudentID| CourseID | Status ID|
--------------------------------
1 | 1 | 1
1 | 2 | 1
1 | 2 | 2
2 | 1 | 3
2 | 1 | 1
我想要的结果是这样的
StudentID| Course | Status|
--------------------------------
1 | Art | Nice
1 | Math | Good
2 | Science | Bad
有人能帮我吗?如何为sql选择该表
<?php $query ="Select StudentID, Course, max(StatusID) from student a, course b, process c
where a.student = c.studentid and b.studentid = c.studentid
group by studentid, processid";
$result=mysql_query($query);
while($row=mysql_fetch_array($result)){
echo $row['StudentID'];
echo $row['Course'];
echo $row['Status'];
工作正常,但状态不是最大状态。。我尝试使用SQL,StatusID是max result
}
?>使用Group by的简单连接应该有效。试试这个
SELECT p.studentid,
c.courseid,
Max(p.statusid) statusid
FROM Status s
JOIN Process p
ON s.StatusID = p.StatusID
JOIN Course c
ON c.CourseID = p.CourseID
GROUP BY p.studentid,
c.courseid
您可以使用自联接来获取每个学生和每个课程的状态id最高的行
select t.*
from Process t
join (select `StudentID`, `CourseID`,max(`Status ID`) `Status ID`
from Process
group by `StudentID`, `CourseID`) t1
using(`StudentID`, `CourseID`,`Status ID`)
另外,不要在表和列名中使用空格,而要在列状态ID中使用uu like。如果您将其表示为状态ID,这将很好,这样您就不需要反勾号。您想知道每门课程的学生的最大状态,对吗?在这种情况下,您需要的是:
SELECT StudentID,
CourseID,
MAX(StatusID)
FROM Process
GROUP BY StudentID, CourseID;
我相信你想要一行不同的studentid,courseID,你想要从中获得最大的地位,如果我是正确的,那么有一个简单的解决方案 请试一试
SELECT studentid,courseid,MAX(statusid) FROM `process`
GROUP BY studentid,courseid
试试这个:
SELECT A.StudentID, A.CourseID, S.Status AS StatusID
FROM (SELECT P.StudentID, P.CourseID, MAX(S.StatusID) AS StatusID
FROM PROCESS P
INNER JOIN STATUS S ON P.StatusID = S.Status
GROUP BY P.StudentID, P.CourseID
) AS A
INNER JOIN STATUS S ON A.StatusID = S.StatusID
您想选择哪个表?您的问题/要求/问题是什么?首先发布它。请共享您尝试过的sql。您在表进程中将列名称为courseID并存储值'ART',对吗?等等,实际上进程中是什么,给定列名还是文本名,数字ID更有意义?理想情况下,您应该有其他一些排序列—应该忽略id的实际值。否则,这是标准问题的变体。您确定您的流程表正确吗?一般来说,您似乎对键id和值之间的差异感到非常困惑,例如statusits仅打印进程中的最大id,即2 | 2 | 3I已使用您提到的数据创建了一个进程表。现在您已经修改了问题,您想要的是actualstatus而不是StatusID。它只是打印进程中的最大id,即2 | 2 | 3您忘记了字母表-“Good”大于“Bad”之后的值。对于完整查询,请参阅更新的fiddle hi,我还想加入其他表以获取一些数据,如时间、类和我想放在哪里,怎么做@M哈立德Junaid@Johendry如果你问另一个问题,并提供关于你想要加入的新表的所有简要信息,并在这里提供链接,以便我可以查看it@M哈立德·朱奈德,我不能再发帖了,直到3点多days@Johendry你能用新表格的样本数据更新你的问题吗?