我在php(mysql)中生成一个报告,
例如:
`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张桌子。
我可以在单个查询中制作它吗?如果我做了?流程变得缓慢?
答案 0 :(得分:217)
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
答案 1 :(得分:23)
如果使用MyISAM表,最快的方法是直接查询统计数据:
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中的报告值是错误的。
答案 2 :(得分:15)
你当然可以使用Ben James所假设的Select Agregation语句,但是这会产生一个包含尽可能多的列的视图。另一种方法可能如下:
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的解决方案。否则我会建议灵活性,你总是可以破解交叉表结构。
答案 3 :(得分:11)
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')
答案 4 :(得分:0)
我知道这是一个旧堆栈,但是我将发布此Multi-SQL select案例
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'
答案 5 :(得分:0)
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