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 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.