当表之间没有物理连接时优化的SQL查询

时间:2015-10-26 20:38:35

标签: mysql sql join subquery sql-optimization

当表之间没有逻辑连接时,我需要帮助编写更优化的SQL查询。我写了一些子查询,但我不满意,因为我重复几乎相同的子查询两次 该计划如下:

create table rate (
  rate_date date,
  value decimal(10,2),
  multiplier integer,
  name varchar(3)
  );

create table amount (
  amount decimal(10,2),
  amount_year date,
  rate_name varchar(3)
  );


我希望AMOUNT表中的每个金额都使用来自RATE表格的乘数和费率值来计算,如此amount / multiplier * rate。两个表的共同点是名称(一些代码标识符)和日期。这些应该用于将数据汇总在一起。仅考虑amount_year的最新费率 如果您愿意提供帮助,可以查看此fiddle。那是我的尝试。

select am.amount / 
    (
      select ra.multiplier 
      from rate ra
      where ra.rate_date = (select max(rate_date) 
                            from rate 
                            where year(rate_date) = year(am.amount_year) and name = am.rate_name) 
        and ra.name = am.rate_name
    ) * (
      select ra.value 
      from rate ra
      where ra.rate_date = (select max(rate_date) 
                            from rate 
                            where year(rate_date) = year(am.amount_year) and name = am.rate_name) 
        and ra.name = am.rate_name
    ) as calculated_amount
    from amount am;

2 个答案:

答案 0 :(得分:2)

您的子查询是相同的,因此您可以在一个中完成工作:

select am.amount / 
       (select ra.multiplier * ra.value
        from rate ra
        where ra.rate_date = (select max(rate_date) 
                              from rate 
                              where year(rate_date) = year(am.amount_year) and name = am.rate_name)  and ra.name = am.rate_name
                             )
       ) as calculated_amount
from amount am;

或者这可以表达为:

select am.amount / 
       (select ra.multiplier * ra.value
        from rate ra
        where year(ra.rate_date) = year(am.amount_year) and name = am.rate_name
        order by ra.rate_date desc
        limit 1
       ) as calculated_amount
from amount am;

如果您愿意,可以使用join where来执行此操作:

select (am.amount / ra.multiplier * ra.value) as calculated_amount
from amount am join
     rate ra
     on ra.name = am.name and
        year(rate_date) = year(am.amount_year)
where ra.date = (select max(r2.rate_date)
                 from rate r2
                 where year(r2.rate_date) = year(r.rate_date) and
                       r2.name = ra.name
                );

对于性能,请从rate(name, rate_date, multiplier, value)开始索引。对于任一查询。

为了获得更好的性能,您可能需要将“year”存储为表格中的单独列。

答案 1 :(得分:1)

您可以使用单个子查询来获取每年的最新倍数和值。然后将其与amount表一起进行划分。

SELECT am.amount / (r2.multiplier * r2.value) AS calculated_amount
FROM amount AS am
JOIN (SELECT YEAR(rate_date) AS year, MAX(rate_date) AS maxdate
      FROM rate
      GROUP BY year) AS r1 ON YEAR(am.rate_date) = r1.year
JOIN rate AS r2 ON r1.maxdate = r2.rate_date