【问题标题】:Optimize the reuse of MySql subquery优化MySql子查询的复用
【发布时间】:2012-01-27 11:54:06
【问题描述】:

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

选择 * (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(从 tbl1 选择 f1 WHERE cond4 ORDER BY o4 LIMIT 1)然后 'something3' WHEN (SELECT f1 FROM tbl1 WHERE cond5 ORDER BY o5 LIMIT 1) then 'something4' END) 作为第 X 列 来自 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 行的表上测试)

【问题讨论】:

    标签: mysql database subquery


    【解决方案1】:

    为什么不只是做联合......是的,它可能会更长一点,但应该更有效率。您的查询是从 tbl1 查询的,不仅在 where 中,而且在 where 条件中,并且在 field 条件中再次查询。为每个 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
    

    【讨论】:

    • 如果我不想在查询有结果的情况下将“某物”添加到 ColumnX,那将起作用。 CASE WHEN query1 THEN "something" WHEN query2 THEN "somethingElse"。
    猜你喜欢
    • 2011-11-27
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多