如何将两个sql表达式合并为一个?

时间:2017-07-07 22:09:25

标签: mysql sql

我有以下问题:

  
      
  • 有必要编写一个查询,输出' item_id' ' price_in_byr'
  •   
  • ' price_in_byr' 的计算方法是表的' 乘以表费率
  • 中汇率最高日期的汇率   

See Schema

我为我的英语道歉,我试着通过例子解释:

  

item_id = 5的货物成本为20欧元,在费率表中,欧元的最大日期是1月12日,当时汇率为25.总计我们的' price_in_byr' 是25 * 20 = 500

我的临时表解决方案:

CREATE TABLE tempRate SELECT currency, MAX(rate) AS maxRate FROM rates GROUP 
BY currency;

SELECT items.item_id,(ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM items
LEFT JOIN tempRate ON items.currency = tempRate.currency;

请告诉我,如何在一个查询中执行此操作?

3 个答案:

答案 0 :(得分:0)

您可以使用子查询:

SELECT 
    items.item_id,(ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM 
    items
    LEFT JOIN 
    (
    SELECT 
        currency, MAX(rate) AS maxRate 
    FROM 
        rates 
    GROUP BY 
        currency
    ) AS tempRate
    ON items.currency = tempRate.currency;

实际上,您可以用(definition of tempRate) AS tempRate替换“tempRate”。

您可以在 dbfiddle here

中查看示例

如果你真的想要* most_recent_rate *,你会做一些完全不同的事情;插入子查询来计算它。此子查询查找给定currency的所有费率,按降序排列exchange_ts(含义时间戳),然后选择前1:

SELECT 
    items.item_id,(ifnull(
    (
        SELECT 
            rate AS most_recent_rate
        FROM 
            rates
        WHERE
            rates.currency = items.currency
        ORDER BY
            exchange_ts DESC
        LIMIT 1    
    )
    , 1) * items.price) AS price_in_byr
FROM 
    items ;

dbfiddle here

答案 1 :(得分:0)

您可以将tempRate查询转换为子查询:

SELECT 
    items.item_id,
    (ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM 
    items
    LEFT JOIN (
        SELECT currency, MAX(rate) AS maxRate 
        FROM rates 
        GROUP BY currency
        ) as tempRate ON items.currency = tempRate.currency;

答案 2 :(得分:0)

我不确定mysql是否支持这个级别的子查询,但看看它是否有效:

          CURRENT BEST VALUE OF HEAT OF FORMATION =  -1161.249249
  cycles=200 pm6 opt singlet eps=80   charge=-1


  C    -3.87724655 +1   1.30585983 +1   4.53273224 +1
  H    -7.60628859 +1   0.53968618 +1   3.72680573 +1
  O    -4.76978297 +1   4.45409715 +1   1.42608903 +1
  H    -4.66890488 +1   4.47267425 +1   2.41952335 +1
  H    -5.59468165 +1   3.93399792 +1   1.27757138 +1


 **********************
 *                    *
 * JOB ENDED NORMALLY *
 *                    *
 **********************