将重复的子查询转换为JOINS

时间:2010-11-22 20:08:54

标签: mysql query-optimization

我有以下查询重复具有不同列选择的选择子查询,我希望我能以更优雅的方式编写它。请注意,第一个选择查询在代码中重复两次,但列选择不同。

SET @date1  = '2010-01-06';
SET @date2  = '2010-07-01';
SET @qdate  = '2010-07-01';
SET @period = 'WEEK';
      (SELECT S.date1, 
              S.date2,
              S.period,
              Q.market,
              Q.ticker,
              Q.close * EXP(S.ratio) AS scenario

        FROM portfolio.scenario S , portfolio.quote Q

        WHERE  
              S.date1 >= @date1 AND
              S.date2 <= @date2 AND
              Q.date  = @qdate AND
              S.series = @series AND
              Q.market = S.market AND 
              Q.ticker = S.ticker)

UNION

      (SELECT T2.date1, 
              T2.date2, 
              T2.period, 
              T1.market, 
              T1.ticker, 
              0 AS scenario
      FROM
                  (SELECT DISTINCT
                          Q.market,
                          Q.ticker

                  FROM portfolio.scenario S , portfolio.quote Q

                  WHERE  
                        S.date1 >= @date1 AND
                        S.date2 <= @date2 AND
                        Q.date  = @qdate AND
                        S.series = @series AND
                        Q.market = S.market AND 
                        Q.ticker = S.ticker) AS T1

            JOIN 

                  (SELECT DISTINCT S.date1, S.date2, S.period
                   FROM portfolio.scenario S
                   WHERE S.series = @series AND
                         S.date1 >= @date1 AND
                         S.date2 <= @date2) AS T2

            WHERE     (T2.date1, 
                       T2.date2, 
                       T2.period, 
                       T1.market, 
                       T1.ticker) 

                    NOT IN 

                        (SELECT S.date1, 
                        S.date2,
                        S.period,
                        Q.market,
                        Q.ticker

                        FROM portfolio.scenario S , portfolio.quote Q

                        WHERE  
                              S.date1 >= @date1 AND
                              S.date2 <= @date2 AND
                              Q.date  = @qdate AND
                              S.series = @series AND
                              Q.market = S.market AND 
                              Q.ticker = S.ticker))

1 个答案:

答案 0 :(得分:0)

我懒得在这里重复你的整个查询,但有一种简单的方法可以使用Case语句替换结果中的字段。

这将允许您根据变量输出不同的字段。

所以

CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END

可以在select子句中使用。 Zhis将允许您根据查询的第3个字段切换字段。