PHP MySQL按两列排序,第一列限制为1个结果

时间:2018-07-19 11:53:06

标签: php mysql

嘿,我有这张桌子:

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的目标是找到两性中年龄最大的学生(这只是一个例子)。 我必须得到的结果如下:

Audrina
Darnell

我为此目的使用此PHP脚本:

<?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>";

?>

我的问题是我可以创建一个仅获取必要的两行结果的MySQL查询吗?

4 个答案:

答案 0 :(得分:2)

其中一种方法是union两个结果:

(SELECT * FROM `pupils` WHERE `Sex` = 'male' ORDER BY Age DESC LIMIT 1) 
UNION
(SELECT * FROM `pupils` WHERE `Sex` = 'female' ORDER BY Age DESC LIMIT 1)

演示here

答案 1 :(得分:2)

尝试一下 select name from pupils where age in (select max(age) from pupils group by sex);

答案 2 :(得分:1)

您可以使用两个单独查询中的result <- setDT(to.merge)[setDT(df), on = .(x, y, time), roll = "nearest", .(x, y, time, val = replace(val, abs(x.time - i.time) > 1, NA))] result

union

答案 3 :(得分:0)

我想会做到的:

SELECT * FROM pupils as p1 
WHERE p1.Sex='male' ORDER BY p1.Age DESC LIMIT 1
UNION
SELECT * FROM pupils as p2 
WHERE p2.Sex='female' ORDER BY p2.Age DESC LIMIT 1