如何正确格式化这四个查询?

时间:2015-11-19 20:30:25

标签: php mysql count

如何正确地将这4个问题拼凑起来......

<?php 
    $units = $query->fetch("SELECT COUNT(*) AS AvailSm FROM units WHERE apartment_name='s'  AND status='A';");
    $units = $query->fetch("SELECT COUNT(*) AS AvailMd FROM units WHERE apartment_name='m'  AND status='A';");
    $units = $query->fetch("SELECT COUNT(*) AS AvailLg FROM units WHERE apartment_name='l'  AND status='A';");
    $units = $query->fetch("SELECT COUNT(*) AS AvailXL FROM units WHERE apartment_name='xl' AND status='A';");
?>

...所以我可以使用以下方法导出每个尺寸单位的数量:

<?php echo $units['AvailSm']; ?>
<?php echo $units['AvailMd']; ?>
<?php echo $units['AvailLg']; ?>
<?php echo $units['AvailXL']; ?>

......如果可能的话。谢谢!

1 个答案:

答案 0 :(得分:3)

您首先要使用GROUP BY,例如:

SELECT apartment_name, COUNT(*) AS AvailForThisType 
FROM units WHERE
apartment_name in('s','m','l','xl')  AND status='A'
Group By apartment_name

然后弄清楚如何更改fetch函数以适应它(即使用apartment_name作为键来构建计数数组)。