优化MySql子查询的重用

时间:2012-01-27 11:54:06

标签: mysql database subquery

我有这个查询可以满足我的需要,但是我觉得我可以改进一下,但我不确定如何。

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,并且LEFT JOINS不起作用,因为查询可能不会返回任何结果。使用FULL OUTER JOIN仿真只需要太长时间。 (在约5000行的表上测试)

1 个答案:

答案 0 :(得分:1)

为什么不做工会......是的,它可能会更长一些,但应该更有效率。您的查询正在从tbl1查询,而不仅仅是在where,而是在where条件中,再次在字段条件中查询。选择每个SELECT ONCE的ONCE标准,并按条件

选择所有5个不同的标准/集/顺序
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