Compare COUNT from two tables

Asked

Viewed 489 times

7

I have two tables and I must return the total of the table with more data, I am doing so:

SELECT CASE WHEN ((select count(*) as `familiar` from tb.familiar)) > 
                 ((select count(*) as `personal` from tb.personal))
                  THEN 0 ELSE 1 END AS total

That way it works, when the table familiar is higher returns 0 and when does not return 1. But as return the value of COUNT? 'Cause when I put my last name (familiar or personal) Count gives syntax error, for example:

SELECT CASE WHEN ((select count(*) as `familiar` from tb.familiar)) > 
                 ((select count(*) as `personal` from tb.personal))
                  THEN familiar ELSE personal END AS total

From the following error:

Unknown column 'familiar' in 'field list'

  • You could put the code that are in trouble, maybe it helps in the answer.

1 answer

6


You’d have to repeat all the code of the two Select count... within the THEN and of ELSE.

Or...

You can make a subselect:

SELECT 
    CASE WHEN FAMILIAR > PERSONAL THEN FAMILIAR ELSE PERSONAL END AS Total
FROM
(
    SELECT 
        (select count(*) from tb.familiar) AS FAMILIAR,
        (select count(*) from tb.personal) AS PERSONAL
) X
  • 1

    I would only put it after END one AS TOTAL to receive a name column.

  • 1

    True! I edited to have the name. Thank you @Gumball

Browser other questions tagged

You are not signed in. Login or sign up in order to post.