来自同一行的 SUM 值,其中多列等于相同值

SUM values from same row where multiple columns equal same value

我正在尝试获取我数据库中每个 "booking" 记录的动物类型数量的输出,数据库结构与此类似。

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']; ?>

非常感谢任何建议或想法。

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;
}
}

检查这个..