2013-03-25 98 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; 

依此類推。