2010-12-14 120 views
1

我寫了這個MySQL查詢:如何優化這個mysql查詢?

SELECT * , 1 AS haschild 
     FROM table2 
     WHERE parentid = '0' 
      AND pid IN (SELECT parentid FROM table2) 
UNION 
SELECT * , 0 
     FROM table2 
     WHERE parentid = '0' 
      AND pid NOT IN (SELECT parentid FROM table2) 
ORDER BY pid 

,但我認爲這是太傻了!查詢 希望你能得到我這個查詢的含義,並指導我寫出更好的一個。

謝謝。

回答

2
SELECT t1.*, 
      IF(t2.parentid IS NULL, 0, 1) AS haschild 
    FROM table2 t1 
LEFT JOIN table2 t2 ON t1.pid = t2.parentid 
    WHERE t1.parentid = 0 
ORDER BY t1.pid 

注:

  1. 創建指數parentid
  2. 如果parentid是一個數字 - 不要把周圍
+1

爲什麼不要把報價放在一邊nd號碼字段? – 2010-12-14 11:50:12

+0

@hd:因爲在某些情況下,由於某些原因,mysql試圖將字段強制轉換爲字符(而不是字符到數字),並且您失去了通過索引優化查詢的機會。 – zerkms 2010-12-14 11:53:35

0

嘗試報價:

SELECT * , CASE WHEN pid IN (SELECT parentid FROM table2) THEN 1 ELSE 0 END AS haschild 
     FROM table2 
     WHERE parentid = '0' 
ORDER BY pid