简体   繁体   中英

How to compare row counts of 3 OR MORE tables and return a BOOLEAN Value?

I can get a BOOLEAN result to say if TWO tables have the same number of rows as per this question and answers: Compare row count of two tables in a single query and return boolean

SELECT 
       CASE WHEN (select count(*) from table1)=(select count(*) from table2)
       THEN 1
       ELSE 0
END AS RowCountResult

I've tried this with 3 tables:

SELECT 
    CASE WHEN (SELECT count(*) from personal)=(SELECT count(*) from exam)=(SELECT COUNT(*) from contact)    
THEN 1 
ELSE 0 
END AS RowCountResult 

but that returns 0, whereas the 3 tables actually have the same number of rows, so it should return 1. Any help appreciated!

An expression like:

a = b = c

is evaluated (from left to right) as:

(a = b) = c

and since (a = b) is a boolean expression it is evaluated as 0 or 1 , so you end up with the evaluation of 1 = c or 0 = c which in your case is (most probably) always false .

You should compare separately a to b and b to c and use the operator AND for the final result, like:

a = b AND b = c

So, your code should be:

SELECT 
  (SELECT count(*) from personal) = (SELECT count(*) from exam)
  AND
  (SELECT count(*) from exam) = (SELECT COUNT(*) from contact) AS RowCountResult

or better with a subquery:

SELECT count1 = count2 AND count2 = count3 AS RowCountResult 
FROM (
  SELECT (SELECT count(*) from personal) count1,
         (SELECT count(*) from exam) count2,
         (SELECT COUNT(*) from contact) count3    
) t 

You don't actually need the CASE expression.

That is because you are comparing the result of a comparison with the third rowcount, ie A=B (which will give a true or false) with C (which in this case is a number).You should get what you expect with eg (A=B)=(B=C), or, in your case

SELECT 
    CASE WHEN 
    ((SELECT COUNT(*) FROM Personal) = (SELECT COUNT(*) FROM Exam))
    = ((SELECT COUNT(*) FROM Contact) = (SELECT COUNT(*) FROM Exam))    
    THEN 1 
    ELSE 0 
    END 
AS RowCountResult 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM