2017-11-01 7 views
0

나는 PHP 코드를 가지고 :SELECT 카운트 2 개 테이블에서 행 및 합계 결과는

$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; 

요점은 그것이 그렇게 안한다 때 때로는 $number 변수가 NULL, 을 반환한다는 것입니다.

나는이 두 테이블에 항상 행을 가지고 있으며 반환 된 결과는 NULL이 아니어야합니다.

2 테이블의 행 수를 합산하는 올바른 방법입니까? 가끔씩 숫자 대신 NULL이 나오는 이유를 모르겠다.

답변

3

글쎄, 난 당신이 진정한 결과를이 쿼리를 실행하고 total_rows의 가치는 당신에게 돌아갑니다 받고

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

처럼 할 제안

아니면 동일한 작업을 수행하는 저장 프로 시저를 만들 수 있습니다 맡은 일. 당신이 한 번에 바로 결과를해야합니다 과 두 번 중간 결과를 가져 오기 위해 DB에 접촉하지 않도록하고 또한 간단합니다 :

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

아래에 설명 된대로 왜 이런 식으로 하나 개의 쿼리 가지 마세요 너의 프로그램!

SELECT 
(select count(*) from table_1) 
+ 
(select count(*) from table_2)