关于mysql:单个查询中的多个select语句

Multiple select statements in Single query

我在php(mysql)中生成一个报告,

例如:

1
2
3
`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`

像这样我有12张桌子。

我可以在单个查询中进行。 如果我做了? 流程变慢了?


1
2
3
4
5
6
7
8
9
10
11
12
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


如果您使用MyISAM表,最快的方法是直接查询统计信息:

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

如果您有InnoDB,则必须使用count()进行查询,因为information_schema.tables中的报告值是错误的。


你当然可以将Ben Agregation声明作为Ben James的假设,但是这将产生一个包含尽可能多的列的视图。另一种方法可能如下:

1
2
3
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;

关于这样的approch的好处是,您可以显式编写Union语句并生成视图或创建临时表,以保存使用变量代替表名从Proc cals连续添加的值。我倾向于更多地使用后者,但这实际上取决于个人偏好和应用。如果您确定表永远不会更改,那么您希望数据采用单行格式,并且您不会添加表。坚持Ben James的解决方案。否则我会建议灵活性,你总是可以破解交叉表结构。


1
2
3
4
5
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')


1
2
3
4
5
6
7
8
SELECT t1.credit,
       t2.debit
FROM   (SELECT Sum(c.total_amount) AS credit
        FROM   credit c
        WHERE  c.status ="a") AS t1,
       (SELECT Sum(d.total_amount) AS debit
        FROM   debit d
        WHERE  d.status ="a") AS t2

我知道这是一个旧的堆栈,但我将发布这个Multi-SQL选择案例

1
2
3
4
5
6
7
8
9
10
    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'