dongshao8566 2014-09-26 12:23
浏览 88
已采纳

使用php检索mysql中两个不同的表列字段的总和

Hey guys I m stuck over this query

I have two different table with same column name but different values with primary key id

Table 1 : q1

id ability_to_delegate communication confidence commitment

1           0                0            1          0          

2           0                0            0          0

3           0                0            0          0

4           1                0            1          0

Table 2 : q2

id ability_to_delegate communication confidence commitment

1           0                0            2          1          

2           0                0            1          1

3           0                0            0          0

4           0                0            1          1

Now what I want is to sum the values of two different tables with same field name but different IDs.

For example I want values of confidence field from table q1 with id = 4 i.e 1 and values of confidence field from table q2 with id = 1 i.e 2 to be added i.e 3.

I tried using union but not getting the rseult

$mresult=mysqli_query($con,"select sum(sm) from 

(select confidence sm from q1 where id='$id' 

union 

select confidence sm from q2 where id='$id') ss");

while ($row1 = mysqli_fetch_assoc($mresult)){
echo "Sum ". $row1['ss'];
}

I m getting warning

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in .... on line 89

Please help me out

  • 写回答

1条回答 默认 最新

  • duanlou2917 2014-09-26 12:35
    关注

    The query to accomplish what you're looking for is

    SELECT `q1`.`confidence` + `q2`.`confidence` AS `TotalConfidence`
    FROM `q1`, `q2`
    WHERE `q1`.`id` = 4
    AND `q2`.`id` = 1
    

    You can plug this into your PHP and substitute the variables where appropriate.

    $mresult=mysqli_query($con,"SELECT `q1`.`confidence` + `q2`.`confidence` AS `TotalConfidence` FROM `q1`, `q2`WHERE `q1`.`id` = '{$q1id}' AND `q2`.`id` = '{$q2id}'");
    
    while ($row1 = mysqli_fetch_assoc($mresult)){
        echo "Sum ". $row1['TotalConfidence'];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化