代码之家  ›  专栏  ›  技术社区  ›  Charles Faiga

如何在mysql 5.1中使用“order by”和“limit”语句进行多表更新

  •  0
  • Charles Faiga  · 技术社区  · 15 年前

    我有两张桌子 事件 固定场所

    CREATE TABLE  `events` (
      `idEvents` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `NumberOfPlaces` int(10) unsigned DEFAULT '0',
      `FpOddsPrice` double DEFAULT '0',
      PRIMARY KEY (`idEvents`),
    ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;
    

    ////////////////////////////////////////////////////////////////

    CREATE TABLE  ` fixedplace ` (
      `idFixedPlacePrice` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `NumberOfRunners` int(10) unsigned DEFAULT NULL,
      `Places` int(10) unsigned DEFAULT NULL,
      `FpOddsPrice` double DEFAULT NULL,
      PRIMARY KEY (`idFixedPlacePrice`)
    ) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1;
    
    
    
    
    Insert Into fixedplace (NumberOfRunners, Places, FpOddsPrice)
    Values
    (0, 0, 0),
    (10, 3, 0.16),
    (13, 4, 0.21);
    

    //////////////////////////////////////////////////////////////

    要访问固定位置数据,我使用以下语句

    SELECT
      Places,
      FpOddsPrice
    FROM FixedPlace as 
    WHERE NumberOfRunners <=  :FNumberOfRunners 
    ORDER BY NumberOfRunners desc
    LIMIT 1
    

    即,如果:fnumberofruners=11,则place为3,fpoddsprice=0.16

    //////////////////////////////////////////////////////////////

    我在写更新声明时遇到问题 将基于fixedplace表中的值更新事件表

    这不起作用

    UPDATE Events as E, FixedPlace as F 
    Set E.Places       = F.Places,
        E.FpOddsPrice  = F.FpOddsPrice
    WHERE E.idEvents = :FidEvents
       And F.NumberOfRunners <=  :FNumberOfRunners
    ORDER BY F.NumberOfRunners desc
    LIMIT 1
    

    它给出了以下错误 “update an order by”的用法不正确

    我该怎么做才能让它工作?

    编辑

    这很管用,但有没有更好的方法

    UPDATE Events as E
    Set E.Places       = (Select Places     FROM FixedPlace WHERE NumberOfRunners <=  :FNumberOfRunners ORDER BY NumberOfRunners desc LIMIT 1),
        E.FpOddsPrice    = (Select FpOddsPrice FROM FixedPlace WHERE NumberOfRunners <=  :FNumberOfRunners ORDER BY NumberOfRunners desc LIMIT 1)
    WHERE E.idEvents = :FidEvents
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   jitter    15 年前

    MySQL UPDATE Syntax 文档

    对于多表语法,请更新 更新名为in的每个表中的行 满足 条件。 在这种情况下,按 无法使用限制 .

        2
  •  0
  •   Andomar    15 年前

    这有点难,因为mysql不允许在子查询中使用limt。

    我要做的是两个独立的查询。第一个已经在您的文章中;第二个是一个简单的更新查询,如:

    UPDATE Events E
    SET  E.Places = :Places
    ,    E.FpOddsPrice = :Price
    WHERE E.idEvents = :FidEvents