Helo, I have this table:
CREATE TABLE `pupils` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`Name` varchar(24) NOT NULL DEFAULT '',
`Sex` varchar(8) NOT NULL DEFAULT '',
`Age` SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_general_ci;
INSERT INTO `pupils` VALUES ( DEFAULT, 'Tom', 'male', 12);
INSERT INTO `pupils` VALUES ( DEFAULT, 'Audrina', 'female', 17);
INSERT INTO `pupils` VALUES ( DEFAULT, 'Darnell', 'male', 15);
INSERT INTO `pupils` VALUES ( DEFAULT, 'Dana', 'female', 11);
INSERT INTO `pupils` VALUES ( DEFAULT, 'Roberta', 'female', 14);
INSERT INTO `pupils` VALUES ( DEFAULT, 'Walton', 'male', 14);
Мy goal is to find the eldest students for both sexes ( this is just an example ). The result I have to get is the following:
Audrina
Darnell
I use this PHP script for this purpose:
<?php
include 'login.php';
function MySqlConnect( ) {
global $host, $sql_username, $sql_password, $db_name;
$con = new mysqli( $host, $sql_username, $sql_password, $db_name );
if( $con->connect_errno ) { echo "ops1"; die( ); }
return $con;
}
function GetNames( $con, &$all_names ) {
global $tbl_pupils;
if(!($result = $con->query( "SELECT Name,Sex FROM $tbl_pupils ORDER BY Sex,Age DESC" ) ) ) { echo "ops2"; die( ); }
$names = [ ];
while( $row = $result->fetch_row( ) ) {
$curr_pupil = end( $names );
if( !strcasecmp( $curr_pupil[1], $row[1] ) ) {
$curr_pupil[0] = $row[0];
$curr_pupil[1] = $row[1];
} else {
$names[ ] = array( $row[0], $row[1] );
}
}
foreach( $names as &$curr_pupil ) $all_names[ ] = $curr_pupil[0];
$result->free_result( );
}
$con = MySqlConnect( );
GetNames( $con, $all_names );
$con->close( );
foreach( $all_names as $name ) echo "$name<br>";
?>
My question is can I create a MySQL query with which to get only the necessary two rows of results?