Executing multiple MySQL queries in a single query?

I know that the request below is not valid, but I just use it as an example as what I'm trying to achieve.

Basically what I want to do is get the COUNT () of all the rows, and then also get the COUNT () string from the rows with the condition clause in one query.

Such as..

SELECT 
    COUNT(*) AS full_amount,
    COUNT(address IF NOT NULL),
    COUNT(name IF NOT NULL)
FROM
   table;

Now, what I'm trying to figure out above is the full count of the table, and I'm also trying to figure out the number of rows in the table, where the "address" and "name" fields are NOT ZERO. Not where they are both not null, but individually.

To clarify, this will be done with a few queries that I am trying to avoid.

SELECT COUNT(*) FROM table AS amount;

SELECT COUNT(*) FROM table AS amount WHERE address IS NOT NULL;

SELECT COUNT(*) FROM table AS amount WHERE name IS NOT NULL;

Are there any better ways to do this than run multiple queries?

+3
2

- COUNT , NULL:

SELECT COUNT(*) AS full_amount,
    COUNT(address) AS has_address,
    COUNT(name) AS has_name
FROM table;

. COUNT (DISTINCT...), , NULL.

+4

, :

 SELECT COUNT(*), 
    SUM(IFNULL(address, 0, 1)) AS address_count, 
    SUM(IFNULL(name, 0, 1)) as name_count
 FROM Table;
0

Source: https://habr.com/ru/post/1769916/


All Articles