我想在我的数据库中获取每个“预订”记录的动物类型数量的输出,数据库结构与此类似。
bid, name, business, animal_type1, animal_size1, animal_type2, animal_size2, animal_type3, animal_size3, animal_type4, animal_size4
示例记录是
1, John Smith, John Smith's Pets, Dog, Small, Dog, Medium, Cat, Small, Dog, Giant, Dog, Large
我想获得这样的输出。
2x Small Dogs
1x Medium Dogs
1x Small Cat
1x Giant Dog
这是我根据教程一直在玩的代码,但没有太多运气,这种方法需要为每种类型和大小运行单独的查询。
<?php
$sql = "SELECT animal_type1,animal_type2,animal_type3,animal_type4,animal_type5 AS total
FROM bookings WHERE bid = '$bid' AND `animal_type1 = 'Dog' AND booking_status = 'Unbooked'";
$result = mysqli_query($GLOBALS["mysqli_ston"], $sql);
$rows = mysqli_fetch_array($result); ?>
<?php echo $rows['COUNT(animal_type1) + COUNT(animal_type2) + COUNT(animal_type3) + COUNT(animal_type4) + COUNT(animal_type5)'] ?>
<?php echo $rows['total']; ?>
非常感谢任何建议或想法。
答案 0 :(得分:0)
for($i=1;$i<=4;$i++)
{
$str_1='animal_type'.$i;
$str_2='animal_size'.$i;
$qry="SELECT CONCAT(COUNT(*),'x') AS N,CONCAT($str_1,' ',$str_2) AS M FROM BOOKINGS WHERE bid = '$bid' GROUP BY CONCAT($str_1,' ',$str_2)";
$res=mysqli_query($qry);
while($result=mysqli_fetch_object($res))
{
echo $result->N.' '.$result->M;
}
}
检查一下..