Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 多列等于相同值的同一行中的值之和_Php_Sql_Count_Sum - Fatal编程技术网

Php 多列等于相同值的同一行中的值之和

Php 多列等于相同值的同一行中的值之和,php,sql,count,sum,Php,Sql,Count,Sum,我试图得到数据库中每个“预订”记录的动物类型数量的输出,数据库结构与此类似 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, Do

我试图得到数据库中每个“预订”记录的动物类型数量的输出,数据库结构与此类似

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

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

对于($i=1;$iN.“。$result->M;
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;
}
}
} }

选中此项。

您可以指定您正在使用的SQL引擎吗?从预订中选择CONCAT(COUNT(*),'x')作为N,CONCAT('animal_type1','animal_size1')作为M,其中bid='bid'按CONCAT分组('animal_type1','animal_size1')。使用循环更改大小和类型后缀,如CONCAT('animal_type1','animal_size1'))…根据您的计数回显结果感谢您的回复,您的代码比我当前的级别要高级得多,我将尝试一下,看看我的表现如何,再次感谢您的回复。查看答案并执行..谢谢,我尝试了此代码,它只是显示空白,所以我在$qry之前添加了回显,得到了此结果,对吗?SEL将海螺(计数(*),'x')作为N,海螺(,'',动物大小1)作为M,从投标为“1”组海螺(,'',动物大小1)的预订中选择海螺(计数(*),'x')作为N,海螺(动物类型1,'',动物大小1)作为M,从投标为“1”组海螺(动物类型1,'',动物大小1)的预订中选择海螺(计数(*),'x')作为M但是仍然是空白,不确定我做错了什么。等等,我还没有添加数据库连接,我会试试。在你的后端编辑器上运行这个,例如php myadmin。你会得到错误提示。