如何在MySQL中创建/使用变量

时间:2015-11-28 20:52:24

标签: mysql variables

我知道在MySQL中你可以做类似SELECT foo AS bar FROM TABLE t;的事情我试图对SELECT command1 FROM table1 AS foo, command2 FROM table2 AS bar, (foo-bar) AS difference;的效果做些什么,但MySQL不允许我那样做。有没有办法在MySQL中执行此操作或我需要获得一些扩展?提前致谢!

1 个答案:

答案 0 :(得分:0)

模式

create table t1
(   id int auto_increment primary key,
    thing varchar(100) not null
);

create table t2
(   id int auto_increment primary key,
    descr varchar(100) not null
);

insert t1(thing) values ('cat'),('dog');
insert t2(descr) values ('meow'),('likes bones');

查询

select t1.thing,t2.descr into @var1,@var2 
from t1 
join t2 
on t2.id=t1.id 
where t1.id=2; -- to avoid Error 1172: Result consisted of more than one row

查看变量

select @var1 as thing,@var2 as descr;
+-------+-------------+
| thing | descr       |
+-------+-------------+
| dog   | likes bones |
+-------+-------------+

选择上述变量的重要部分是将结果集限制为最多1行。