PHP SQL在1个查询中

1 php mysql

对不起,简单的猜测.我是Sql的新手.所以,我有一个sql查询的coouple,我想在1个查询中写这个sql!

$sql1=select 'max(id) as max1 FROM table where status_id=1 LIMIT 1';
$sql2=select 'max(id) as max2 FROM table where status_id=2 LIMIT 1';
$sql3=select 'max(id) as max3 FROM table where status_id=3 LIMIT 1';
$sql4=select 'max(id) as max4 FROM table where status_id=4 LIMIT 1';

$query1=mysql_query($sql1);
$fetch1=mysql_fetch_array($query1);
$query2=mysql_query($sql2);
$fetch2=mysql_fetch_array($query2);
$query3=mysql_query($sql3);
$fetch3=mysql_fetch_array($query3);
$query4=mysql_query($sql4);
$fetch4=mysql_fetch_array($query4);

echo 'Max ID numbers are:'.$fetch1['max1'].'; '.$fetch2['max2'].'; '.$fetch3['max3'].'; '.$fetch4['max4'].'';
Run Code Online (Sandbox Code Playgroud)

如何在一个查询中使用写入这4个sql并获取合适的ID?我试过MYSQL UNION,不是任何结果.

Sir*_*rko 5

使用此查询

SELECT `status_id`, 
       max(`id`) as `max` 
FROM table 
GROUP BY `status_id`
Run Code Online (Sandbox Code Playgroud)

这将为您提供所有对status_id和相应的max(id)每个status_id.您可以在normal(while)循环中获取结果.

标准免责声明:mysql_不推荐使用各种功能.请改用PDOmysqli.