doupu0619 2015-05-05 11:48
浏览 35
已采纳

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

I am trying to get an output of the amount of animal types for each "booking" record in my database, the database structure is similar to this.

bid, name, business, animal_type1, animal_size1, animal_type2, animal_size2, animal_type3, animal_size3, animal_type4, animal_size4

An example record would be

1, John Smith, John Smith's Pets, Dog, Small, Dog, Medium, Cat, Small, Dog, Giant, Dog, Large

I am trying to get an output like this.

2x Small Dogs
1x Medium Dogs
1x Small Cat
1x Giant Dog

This is the code I have been playing with based on tutorials but not having much luck, and this method would require running a separate query for each type and size.

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

Any suggestions or ideas are much appreciated.

  • 写回答

1条回答 默认 最新

  • dongyingdao8867 2015-05-05 12:01
    关注
    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;
    }
    }
    

    check this..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度