php mysql按两列排序,每列限制1个结果

0qx6xfy6  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(310)

这个问题在这里已经有答案了

获得每组分组结果的前n个记录(11个答案)
sql仅选择列上具有最大值的行[重复](27个答案)
两年前关门了。
你好,我有这张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的目标是为男女找到年龄最大的学生(这只是一个例子)。我得到的结果如下:

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查询,用它只获得所需的两行结果吗?

pinkon5k

pinkon5k1#

其中一个方法是 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)

此处演示

bkhjykvo

bkhjykvo2#

试试这个 select name from pupils where age in (select max(age) from pupils group by sex);

ca1c2owp

ca1c2owp3#

你可以用 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);
x8goxv8g

x8goxv8g4#

我想这样就可以了:

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

相关问题