Varias sentencias select en Una sola consulta


Estoy generando un informe en php (mysql),

Ex:

`select count(id) as tot_user from user_table
 select count(id) as tot_cat from cat_table
 select count(id) as tot_course from course_table`

Así tengo 12 tablas.

Puedo hacerlo en una sola consulta. Si lo hiciera? Proceso se vuelve lento?

 80
Author: boss, 2009-11-21

5 answers

SELECT  (
    SELECT COUNT(*)
    FROM   user_table
    ) AS tot_user,
    (
    SELECT COUNT(*)
    FROM   cat_table
    ) AS tot_cat,
    (
    SELECT COUNT(*)
    FROM   course_table
    ) AS tot_course
 200
Author: sathish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-21 11:46:52

Si utiliza tablas MyISAM, la forma más rápida es consultar directamente las estadísticas:

select table_name, table_rows 
     from information_schema.tables 
where 
     table_schema='databasename' and 
     table_name in ('user_table','cat_table','course_table')

Si tienes InnoDB tienes que consultar con count() como el valor reportado en information_schema.tables está mal.

 22
Author: Pentium10,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-13 09:37:50

Ciertamente puede usarnos la instrucción a Select Agregation Postulada por Ben James, Sin embargo, esto resultará en una vista con tantas columnas como tablas tenga. Un método alternativo puede ser el siguiente:

SELECT COUNT(user_table.id) AS TableCount,'user_table' AS TableSource FROM user_table
UNION SELECT COUNT(cat_table.id) AS TableCount,'cat_table' AS TableSource FROM cat_table
UNION SELECT COUNT(course_table.id) AS TableCount, 'course_table' AS TableSource From course_table;

Lo bueno de un enfoque como este es que puede escribir explícitamente las declaraciones de Unión y generar una vista o crear una tabla temporal para mantener los valores que se agregan consecutivamente desde cals de Proc usando variables en lugar de los nombres de sus tablas. Tiendo a ir más con el último, pero realmente depende de la preferencia personal y la aplicación. Si está seguro de que las tablas nunca cambiarán, desea que los datos estén en un formato de una sola fila y no agregará tablas. sigue con la solución de Ben James. De lo contrario, te aconsejo flexibilidad, siempre puedes hackear una estructura de pestañas cruzadas.

 13
Author: Miguel Castaneda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-01 22:35:58
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) =  ('10544175A') 
 UNION  
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('10328189B') 
 UNION  
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('103498732H')
 12
Author: net.tunneler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-02 14:01:11

Sé que esta es una pila antigua, pero publicaré este caso de selección Multi-SQL

    SELECT bp.bizid, bp.usrid, bp.website, 
ROUND((SELECT SUM(rating) FROM ratings WHERE bizid=bp.bizid)/(SELECT COUNT(*) FROM ratings WHERE bizid=bp.bizid), 1) AS 'ratings', 
(SELECT COUNT(*) FROM bzreviews WHERE bizid=bp.bizid) AS 'ttlreviews', 
bp.phoneno, als.bizname, 
(SELECT COUNT(*) FROM endorsment WHERE bizid=bp.bizid) AS 'endorses'
, als.imgname, bp.`location`, bp.`ownership`, 
(SELECT COUNT(*) FROM follows WHERE bizid=bp.bizid) AS 'followers', 
bp.categories, bp.openhours, bp.bizdecri FROM bizprofile AS bp 
INNER JOIN alluser AS als ON bp.usrid=als.userid 
WHERE als.usertype='Business'
 0
Author: Niclausel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 13:53:53