2012-01-27 69 views
-1

我有這個查詢,我需要,但我覺得我可以改善一點,但我不確定如何。優化MySql子查詢的重用

 
SELECT * 
    (CASE WHEN (SELECT f1 FROM tbl1 WHERE cond1 ORDER BY o1 LIMIT 1) then 'something0' 
      WHEN (SELECT f1 FROM tbl1 WHERE cond2 ORDER BY o2 LIMIT 1) then 'something1' 
      WHEN (SELECT f1 FROM tbl1 WHERE cond3 ORDER BY o3 LIMIT 1) then 'something2' 
      WHEN (SELECT f1 FROM tbl1 WHERE cond4 ORDER BY o4 LIMIT 1) then 'something3' 
      WHEN (SELECT f1 FROM tbl1 WHERE cond5 ORDER BY o5 LIMIT 1) then 'something4' 
     END) as columnX 
     FROM tbl1 
     WHERE another_cond1 AND f1 = (SELECT f1 FROM tbl1 WHERE cond1 ORDER BY o1 LIMIT 1) 
     OR another_cond2 AND f1 = (SELECT f1 FROM tbl1 WHERE cond2 ORDER BY o2 LIMIT 1) 
     OR another_cond3 AND f1 = (SELECT f1 FROM tbl1 WHERE cond3 ORDER BY o3 LIMIT 1) 
     OR another_cond4 AND f1 = (SELECT f1 FROM tbl1 WHERE cond4 ORDER BY o4 LIMIT 1) 
     OR another_cond5 AND f1 = (SELECT f1 FROM tbl1 WHERE cond5 ORDER BY o5 LIMIT 1) 

我試圖用變量,但沒有成功,尤其是閱讀MySQL的文檔,它說後「作爲一般規則,你不應該賦值給一個用戶變量和相同的語句中讀出的值」 。

任何幫助將不勝感激。

編輯

我嘗試連接,並與左JOINS不會起作用,因爲查詢可能不會返回任何結果。使用FULL OUTER JOIN仿真只需要很長時間。 (在〜5000行的桌子上測試)

回答

1

爲什麼不只是做工會......是的,它可能會更長一點,但應該更有效率。你的查詢是從tbl1查詢的,不僅僅是在哪裏,而是在哪裏,以及在現場條件下。選擇標準每一次選擇和工會一旦與條件

select f1 as ColumnX 
    from tbl1 
    where another_cond1 and cond1 
    order by o1 
    limit 1 
UNION ALL 
select f1 as ColumnX 
    from tbl1 
    where another_cond2 and cond2 
    order by o2 
    limit 1 
UNION ALL 
select f1 as ColumnX 
    from tbl1 
    where another_cond3 and cond3 
    order by o3 
    limit 1 
UNION ALL 
select f1 as ColumnX 
    from tbl1 
    where another_cond4 and cond4 
    order by o4 
    limit 1 
UNION ALL 
select f1 as ColumnX 
    from tbl1 
    where another_cond5 and cond5 
    order by o5 
    limit 1 
+0

所有5個不同的標準/套/訂單,如果我不想加入「東西」給ColumnX如果查詢結果這將工作。 CASE當query1那麼「某事」什麼時候query2那麼「somethingElse」。 – Andrew 2012-01-27 13:29:02