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

图片转代码服务由CSDN问答提供 功能建议

嘿伙计们我坚持这个查询

我有两个不同的表 具有相同列名但具有主键ID的不同值

表1:q1

  id ability_to_delegate communication 置信度承诺
 
1 0 0 1 0 
 
2 0 0 0 0 
 
3 0 0 0 0 
 
4 1 0 1 0 
   
 
 

表2:q2

  id ability_to_delegate通信置信度承诺
 
1 0 0 2 1 
 
2 0 0 1 1 
 \  n3 0 0 0 0 
 
4 0 0 1 1 
   
 
 

现在我想要的是将具有相同字段名称的两个不同表的值相加 但是不同的ID。

例如,我希望表q1中的置信区域的值为id = 4,即1表示来自表q2的置信区域的值,其中id = 1,即2将被添加,即 3。

我尝试使用union但没有得到rseult

  $ mresult = mysqli_query($ con,“select sum(sm) 来自
 
(从q1中选择置信度sm,其中id ='$ id'
 
union 
 
选择来自q2的置信度sm,其中id ='$ id')ss“); 
 
而($ row1 =  mysqli_fetch_assoc($ mresult)){
echo“Sum”。  $ row1 ['ss']; 
} 
   
 
 

我收到警告

 警告:mysql_fetch_assoc(  )期望参数1是资源,在第89行中给出的对象
   
 
 

请帮帮我

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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'];
    }
    
    打赏 评论

相关推荐 更多相似问题