2013-08-28 92 views
0

我希望能够在查询中创建临时变量 - 而不是存储过程或函数 - 不需要声明和设置,以便我不需要通过我称之为查询参数。在查询中创建临时变量

试图向这方面努力:

Select field1, 
     tempvariable=2+2, 
     newlycreatedfield=tempvariable*existingfield 
From 
     table 
从这个

离开:

DECLARE @tempvariable 
SET @tempvariable = 2+2 
Select field1, 
     [email protected]*existingfield 
From 
     table 

谢谢您的时间

我可能过于复杂的例子;更简单地说,以下给出无效列名QID

Select 
QID = 1+1 
THN = QID + 1 

如果这是在一个查询中,是否有解决方法?子查询

Select field1, tempvariable, 
     (tempvariable*existingfield) as newlycreatedfield 
from (select t.*, (2+2) as tempvariable 
     from table t 
    ) t; 

不幸的是,MySQL有实际实例化的倾向(即创建)派生表:

+0

有你不想使用存储过程的原因? – acutesoftware

+0

如果我已经完成了,我可能会这样做,但是这几行代码会包含数以千计的其他计算数据,并且这些数据会在更大的查询中出现。谢谢 – user2723494

回答

0

你可以做这样的事情:

SELECT field1, tv.tempvariable, 
     (tv.tempvariable*existingfield) AS newlycreatedfield 
FROM table1 
INNER JOIN (SELECT 2+2 AS tempvariable) AS tv 

见SQLFIDDLE:

SELECT var.QID, 
(var.QID + 1) AS THN 
FROM (SELECT 1+1 as QID) AS var 

见SQLFIDDLE:http://www.sqlfiddle.com/#!2/8b0724/8/0

而在你的简化,例如指http://www.sqlfiddle.com/#!2/d41d8/19140/0

+1

完美。 我结束了使用第一个例子,但我的查询迫使我加入它的东西,所以我只是,“ON 1 = 1”。 – user2723494

1

你可以用子查询做到这一点。大多数其他数据库足够聪明以避免这种情况。

你可以赌的是下面的工作:

Select field1, (@tempvariable := 2+2) as tempvariable, 
     (@tempvariable*existingfield) as newlycreatedfield 
From table t; 

这是一场赌博,因为MySQL不能保证第二个参数之前,第三估算的。它似乎在实践中起作用,但不能保证。

+0

这很有趣也很有帮助。我感谢你的回应。 – user2723494

+0

第二次赌博抛出“必须声明标量变量tempvariable”错误。 – user2723494

+0

而第一个抛出“无效列名” – user2723494