doujuchuan9915 2017-11-01 01:17
浏览 173
已采纳

SELECT计算来自2个表的行并对结果求和

I have the PHP code:

$query = mysqli_query($mysqli, "SELECT * FROM `table_1`");
$result = mysqli_num_rows($query);

$queryTwo = mysqli_query($mysqli, "SELECT * FROM `table_2`");
$resultTwo = mysqli_num_rows($queryTwo);

$number =  $result + $resultTwo;
return $number;

The point is that sometimes, the $number variable is returning NULL, when it should not supposed to do that.

I have always rows in those 2 tables, and the returned result should not be NULL, ever.

Is this a correct approach to sum the number of rows from 2 tables? I don`t understand why sometimes I get NULL instead of a number.

  • 写回答

2条回答 默认 最新

  • doushi5024 2017-11-01 01:29
    关注

    Well, I would suggest you to do it like

      select ( select count(*) from Table1 ) + ( select count(*) from Table2 ) 
      as total_rows
    

    executing this query and getting the value of total_rows will return you true result

    Or you can create a stored procedure to do the same thing. as explained below

    CREATE PROCEDURE sp_Test
    AS
    -- Create two integer values
    DECLARE @tableOneCount int, @tableTwoCount int
    
    -- Get the number of rows from the first table
    SELECT @tableOneCount = (SELECT COUNT(*) FROM Table1
                             WHERE WhereClause)
    SELECT @tableTwoCount = (SELECT COUNT(*) FROM Table2
                             WHERE WhereClause)
    
    -- Return the sum of the two table sizes
    SELECT TotalCount = @tableOneCount + @tableTwoCount
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100