简体   繁体   中英

SELECT values from two different rows

I am working with a table that has

session_id : patient_id : efficiency_score

4871 : 32 : 99

4872 : 32 : 100

4872 : 32 : 50

My PHP code to select efficiency_score looks like this:

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.

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?

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. 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 .

You can also use aggregate functions MIN() , AVG() , STDDEV() , COUNT(*) , and the like.

If you need to summarize a subset of the table you can specify a WHERE clause like this:

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:

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.

SELECT session_id, MAX(efficiency_score) AS efficiency_score FROM table1 GROUP BY session_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM