MySql保持重用SQL查询的结果

时间:2011-10-26 13:00:10

标签: mysql sql select

真的有两个问题:

SELECT CurrencyRateID, Rate, Markup
FROM currency_rate 
WHERE CurrencyID = (SELECT CurrencyID FROM currency WHERE BaseCurr = 1) **A** AND
DateTime = (SELECT MAX(DateTime) 
            FROM currency_rate 
            WHERE CurrencyID = **B**)
  1. 为什么这个查询会给我一个 错误代码:1054。“字段列表”中的未知列'CurrercyID'
  2. 如何使用B
  3. 中第一个SELECT语句A的结果

2 个答案:

答案 0 :(得分:1)

检查货币表中是否存在currencyID列并以这种方式更改查询,因此您可以在where子句中使用语句A.

SELECT CurrencyRateID, Rate, Markup
FROM currency_rate cr inner join 
   (SELECT CurrencyID FROM currency WHERE BaseCurr = 1) **A**
   ON cr.CurrencyID = a.CurrencyID 
WHERE cr.DateTime = (SELECT MAX(DateTime) 
            FROM currency_rate 
            WHERE CurrencyID = A.CurrencyID)

答案 1 :(得分:1)

希望您的currency_rate表具有唯一标识符列。

如果是,您可以将查询A和B合并到WHERE子句中的单个查询...

SELECT
  CurrencyRateID, Rate, Markup
FROM
  currency_rate 
WHERE
  uniqueID = (
              SELECT uniqueID
              FROM   currency_rate
              WHERE  CurrencyID = (SELECT CurrencyID FROM currency WHERE BaseCurr = 1)
              ORDER BY DateTime DESC LIMIT 1
             )

如果没有,你可能只需要重复一遍......

SELECT CurrencyRateID, Rate, Markup
FROM currency_rate 
WHERE CurrencyID = (SELECT CurrencyID FROM currency WHERE BaseCurr = 1)
AND DateTime = (SELECT MAX(DateTime) 
            FROM currency_rate 
            WHERE CurrencyID = (SELECT CurrencyID FROM currency WHERE BaseCurr = 1))

注意:即使代码重复,MySQL很可能会注意到重复,只执行一次查询。

修改

我刚注意到你可以简化第一个选项,只使用子查询......

  SELECT CurrencyRateID, Rate, Markup
  FROM   currency_rate
  WHERE  CurrencyID = (SELECT CurrencyID FROM currency WHERE BaseCurr = 1)
  ORDER BY DateTime DESC LIMIT 1