2013-03-25 96 views
0

我试图一次为查询选择3个表。我想知道确定每个表返回多少行的最佳方法是什么?MySQL多个SELECT语句计数结果按表返回

这样做独立,我有

SELECT * from tableA 
SELECT * from tableB 
SELECT * from tableC 

如果我这样做,这样一来,我可以看到每个选择多少行返回。我希望一次选择所有这些我已经成功完成的工作,但我想知道如何为每个返回的表提取结果。下面的示例查询:

SELECT * from tableA ta WHERE id=100 
SELECT * from tableB tb where pid=100 
SELECT * from tableC tc where cid = 100 

这只是一个这样做的问题吗?

SELECT (count(id) from tableA where id=100) as count_tableA, 
SELECT * from tableA ta WHERE id=100,  
SELECT (count(pid) from tableB where id=100) as count_tableB, 
SELECT * from tableB tb where pid=100, 
SELECT (count(id) from tableB where cid=100) as count_tableC, 
SELECT * from tableC tc where cid = 100 

的总体目标是通过避免每次3个查询来提高性能,但是,我需要隔离多少行从返回的每个表回升。

+1

你是否以某种方式连接在一起? – 2013-03-25 16:56:26

+1

你用什么来运行查询?大多数Db驱动程序支持某种“返回行数” – ethrbunny 2013-03-25 17:01:10

+0

我正在使用phpMyAdmin。 @GreenDemon,这些查询是我的加入方法,并且他们工作正常,我只是想确认这是实现此目的的最有效方式。 – 2013-03-25 17:15:53

回答

0

那么,你真的不能避免查询。您必须查询每个表以获取行,并且需要全表扫描。

您可以通过在tableA(id)tableB(id)tableC(cid)上创建索引来优化计数。

您也可以获取应用程序层中的行,然后再进行计数。

查询的语法不正确。也许你的意思是:

select (SELECT count(id) from tableA where id=100) as count_tableA, a.* 
from TableA 
where id = 100; 

依此类推。