[英]SELECT values from two different rows
I am working with a table that has 我正在使用一张桌子
session_id : patient_id : efficiency_score session_id:Patient_id:效率得分
4871 : 32 : 99 4871:32:99
4872 : 32 : 100 4872:32:100
4872 : 32 : 50 4872:32:50
My PHP code to select efficiency_score looks like this: 我用来选择efficiency_score的PHP代码如下所示:
while($row = mysql_fetch_assoc($result)){
$efficiency_score[$c][$k] = $row['efficiency_score'];
}
mysql_free_result($result);
and that's inside 2 for loops which explains the multidimensional array. 在2个for循环中,它解释了多维数组。
However, that code selects through every row in the table and I just want the maximum 但是,该代码选择了表中的每一行,而我只想要最大的
efficiency_score
for each 每个
session_id
How can I find the maximum efficiency_score and only have 1 efficiency_score per session_id? 如何找到最大的efficiency_score,每个session_id只有1个efficiency_score?
This is easy. 这很容易。 Use an aggregate query.
使用汇总查询。
SELECT session_id, MAX(efficiency_score) AS efficiency_score
FROM your_table
GROUP BY session_id
It's part of what SQL does beautifully and efficiently. 这是SQL精美高效地工作的一部分。 If you create a compound index on
(session_id, efficiency_score)
this query will be very fast indeed because MySQL can satisfy it using a loose index scan . 如果在
(session_id, efficiency_score)
上创建复合索引(session_id, efficiency_score)
该查询确实非常快,因为MySQL可以使用松散索引scan来满足它。
You can also use aggregate functions MIN()
, AVG()
, STDDEV()
, COUNT(*)
, and the like. 您还可以使用聚合函数
MIN()
, AVG()
, STDDEV()
, COUNT(*)
等。
If you need to summarize a subset of the table you can specify a WHERE
clause like this: 如果需要汇总表的子集,则可以指定
WHERE
子句,如下所示:
SELECT session_id, MAX(efficiency_score) AS efficiency_score
FROM your_table
WHERE session_id >= 1000 /* or whatever filter criteria */
GROUP BY session_id
If you want to filter on aggregate results you can specify a HAVING clause, like this: 如果要对汇总结果进行过滤,可以指定一个HAVING子句,如下所示:
SELECT session_id, MAX(efficiency_score) AS efficiency_score
FROM your_table
GROUP BY session_id
HAVING MAX(efficiency_score) <= 80 /*or whatever filter criterion*/
You're make it too hard on yourself. 你对自己太难了。 You can get the results from MySQL without the loops.
您可以从MySQL获得结果而无需循环。
SELECT session_id, MAX(efficiency_score) AS efficiency_score FROM table1 GROUP BY session_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.