PCDVD數位科技討論區

PCDVD數位科技討論區 (https://www.pcdvd.com.tw/index.php)
-   七嘴八舌異言堂 (https://www.pcdvd.com.tw/forumdisplay.php?f=12)
-   -   想請問關於資料庫Query的事情.. (https://www.pcdvd.com.tw/showthread.php?t=788339)

student 2008-04-09 11:54 PM

想請問關於資料庫Query的事情..
 
想請問各位一個情況 , 當有兩個將近70萬筆資料的資料表, 需要從兩個資料表作關聯, 取出50~100筆的資料, 想請問哪種作法會比較好?
以效能 或是 系統架構 或是 程式可讀性來說


1. select a.id, sum(b.price) from a, b where a.id = b.a_id group by a.id

2. select a.id, b.price_total from a left join (select a_id, sum(b.price) as price_total from b group by a_id) b on a.id = b.a_id

3. q = db.query(select id from a)

while (not q.eof)
q2 = select sum(price) from b where a_id = & q.id
end while

小弟覺得 1, 2差異不大
但是3 應該是最慢的...

但是有可能因為 q2 的執行時間很短, 所以很多個 簡單的query 會比一個複雜的query來得快??
不好意思, 舉的例子 , 可能不夠明顯, 大家可以想像情況是更複雜, 或是資料筆數更多

michelle_lai529 2008-04-10 12:33 AM

引用:
作者student
想請問各位一個情況 , 當有兩個將近70萬筆資料的資料表, 需要從兩個資料表作關聯, 取出50~100筆的資料, 想請問哪種作法會比較好?
以效能 或是 系統架構 或是 程式可讀性來說


1. select a.id, sum(b.price) from a, b where a.id = b.a_id group by a.id

2. select a.id, b.price_total from a left join (select a_id, sum(b.price) as price_total from b group by a_id) b on a.id = b.a_id

3. q = db.query(select id from a)

while (not q.eof)
q2 = select sum(price) from b where a_id = & q.id
end while

小弟覺得 1, 2差異不大
但是3 應該是最慢的...

但是有可能因為 q2 的執行時間很短, 所以很多個 簡單的query 會比一個複雜的query來得快??
不好意思, 舉的例子 , 可能不夠明顯, 大家可以想像情況是更複雜, 或是資料筆數更多

大概知道你的意思,以前有想過這個問題,應該是 (快2>1>3慢)2的方式可以先初步篩選掉資料,再來做結合,可以減少結合後的量,降低後續的查詢負擔;1的方式則是先結合再來選擇想要的資料,如果兩個資料表都很龐大,結合的過程跟資料量更是可觀,後續再來搜尋效率自然差;3則是捨棄資料庫軟體本身的處理技術,以程式方式去處理,不斷的對資料庫做查詢,這個我有搞過,效率真的差...
想是這樣想,1跟2沒真的測試比較過

sazabijiang 2008-04-11 06:24 PM

引用:
作者student
想請問各位一個情況 , 當有兩個將近70萬筆資料的資料表, 需要從兩個資料表作關聯, 取出50~100筆的資料, 想請問哪種作法會比較好?
以效能 或是 系統架構 或是 程式可讀性來說


1. select a.id, sum(b.price) from a, b where a.id = b.a_id group by a.id

2. select a.id, b.price_total from a left join (select a_id, sum(b.price) as price_total from b group by a_id) b on a.id = b.a_id

3. q = db.query(select id from a)

while (not q.eof)
q2 = select sum(price) from b where a_id = & q.id
end while

小弟覺得 1, 2差異不大
但是3 應該是最慢的...

但是有可能因為 q2 的執行時間很短, 所以很多個 簡單的query 會比一個複雜的query來得快??
不好意思, 舉的例子 , 可能不夠明顯, 大家可以想像情況是更複雜, 或是資料筆數更多


1 跟 2 都是 JOIN, 本質上是一樣的, 差別在於 1 先取A跟B的交集後才運算加總, 2 先針對B全部資料加總, 然後才挑出與A的交集. 感覺1比2快.
3 應該最慢.

阿, 好冷門的話題 ^^a


所有的時間均為GMT +8。 現在的時間是07:55 AM.

vBulletin Version 3.0.1
powered_by_vbulletin 2026。