Mysql Query - Count separate table fields

Asked

Viewed 229 times

1

I need to create a view in Mysql where return the following result.

Col1 | Col2
Total Tab1 | Total Tab2

I am using UNION in the form below, but the result comes as follows:

col1
201
5699

CREATE VIEW `dashboards` AS (
  select 
    count(`clientes`.`id`) AS `col1` 
  from 
    `clientes`) union all (
  select 
    count(`titulos`.`id`) AS `col2` 
  from 
    `titulos`);

But I need it to return as columns and not as lines.

Someone can help me?

2 answers

2

I usually do this:

select 
    count(clientes.id) as coluna1, count(titulos.id) as coluna2, sum(titulos.valor) as total
from
    clientes, titulos

Returns something like this:

coluna1 | coluna2 | total
  10    |    25   |   50

If you need more columns with some formula call in select added comma to separate.

  • Perfect, just needed to turn into view, @Shura16.

1

Explanation

You can develop your query by making a subquery a field. Use the example below as the basis.

Example

  CREATE VIEW `dashboards` AS (
      SELECT (
      select 
        count(`clientes`.`id`) 
      from 
        `clientes`) AS `col1`,(
      select 
        count(`titulos`.`id`)  
      from 
        `titulos`) AS `col2`;

Browser other questions tagged

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