方法一:
sql = "select {xxx} from student A,class B where A.class_id=B.id and A.id in {xxxx}"res = excute(sql)
方法二:
sql = "select * from student where id in {xxxx}"res = excute(sql)foreach(res as v){ sql2 = "select {xxx} from class where id = v[class_id]"; res2 = excute(sql2) res[xxx] = res2[xxx]}
很初級的問題,不過還是問一下
我之前對這種情況都是用方法一的,覺得沒商量;
但最近發現有人用第二種方法,內部系統,訪問量小,所以也沒啥影響,但他說第一種會增加mysql壓力,可能會造成mysql故障,我就懷有遲疑態度了。
請比較熟悉的人幫我分析一下,謝謝
回複內容:
方法一:
sql = "select {xxx} from student A,class B where A.class_id=B.id and A.id in {xxxx}"res = excute(sql)
方法二:
sql = "select * from student where id in {xxxx}"res = excute(sql)foreach(res as v){ sql2 = "select {xxx} from class where id = v[class_id]"; res2 = excute(sql2) res[xxx] = res2[xxx]}
很初級的問題,不過還是問一下
我之前對這種情況都是用方法一的,覺得沒商量;
但最近發現有人用第二種方法,內部系統,訪問量小,所以也沒啥影響,但他說第一種會增加mysql壓力,可能會造成mysql故障,我就懷有遲疑態度了。
請比較熟悉的人幫我分析一下,謝謝
這種問題的原則基本上就是如果能很簡單地用 SQL 算,就在資料庫算,然後緩衝結果。
所以個人偏好方法一。
能用SQL算就在資料庫裡進行運算吧,= =難道自己寫的php語句還會比SQL執行的運算效率高?不要把mysql想的太脆弱。
盡量簡化代碼,所以。。第一種。
第一種雖然說是Join查詢,實際上只有一次訪問資料庫,加上索引不會慢
第二種肯定不會用,死傷~
第一種更簡介明了,一般用第一種。
實際哪種效能更好會跟 student和 class兩個表相對大小有關。
如果第二種方式系統負載低,其實可以把sql 最佳化成這樣:
sql = "select {xxx} from (select * from student where id in (1,2,3))A,class B where A.class_id=B.id "
如果class表的資料可以不每次從資料庫查,全部緩衝下來的話,第二種思想還可以。畢竟class不會太多
第一種裡面有串連操作,DB在進行串連操作時很費勁(特別是表的記錄很多時),而查詢操作基本很快.
首先一個, 你的第二個sql 明顯給的不對了. 在 程式中做join, 起碼我們應該這麼寫:
偽碼:
sql = "select * from student where id in {xxxx}"res = excute(sql)string idsforeach(res as v){ // append v[class_id] to ids.}// ids is now like "1, 3, 4"sql2 = "select {xxx} from class where id in ( $ids )";res2 = excute(sql2)
這樣只需要兩次查詢, 而你的實現明顯 在黑 第二種 方式 啊.
關於在 sql裡還是 在程式裡做 join, High Performance Mysql 裡有討論, 第三版, 第六章, Complex Queries Versus Many Queries, 和 Join Decomposition 兩節.
把 多表join 拆為 多個單表查詢, 有以下優勢(具體細節自己看書啦):
• Caching can be more efficient.
• Executing the queries individually can sometimes reduce lock contention.
• Doing joins in the application makes it easier to scale the database by placing tableson different servers.
• The queries themselves can be more efficient.
• You can reduce redundant row accesses.
• To some extent, you can view this technique as manually implementing a hashjoin instead of the nested loops algorithm MySQL uses to execute a join. A hash join might be more efficient.> undefined> undefined> undefined> undefined
額,顯然是在用第一種啊
原因?
各位叔叔姐姐大爺大媽,求考慮下,sql的主要用途是幹嘛的?
sql script的計算數量級是多少的?
excute 貌似不是T-SQL92規範中支援的吧?
樓上說的沒錯,樓主絕對是進階黑
我想說,如何你想混合計算,那起碼中間的foreach 傳回值相關的東西,你丟該程式去幹行嗎
summary
如果這裡你不選方法一,那你就當我什麼都沒說
不是偏好問題,是堆代碼的原則性問題:1.先儘可能降低SQL文發行次數。 2.再最佳化SQL文執行效率。
方法二把發行SQL文寫在迴圈代碼裡,是寫代碼的大忌,無論你做的東西有多麼的輕量級。
PS:SQL文基本不可能有得不到的結果集,所以不要用多次發行SQL文的方式來解決查詢結果集拼湊問題。
肯定不會用第二種,因為mysql再慢也比當前語言實現的快,而且查詢在語句端更容易最佳化,sql更加容易維護。