对不起,我只是简单的留言。我是Sql新手。所以,我有一个sql查询的couple,我想在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'].'';

如何使用在一个查询中编写这4个sql并获取适当的ID?我试过MYSQL联合,没有结果。

最佳答案

使用group by

select status_id, max(id) as maxValue FROM `table`
where status_id in (1,2,3,4) group by status_id

10-05 20:11
查看更多