我有一个比较长的联合选择:
select A, B from table1 where C='xxx'
union select A, B from table2 where C='xxx'
union select A, B from table3 where C='xxx'
...
我想把xxx定义为一个用户定义的变量,这样我就不用重复这个条件很多次了。不幸的是,我的MySQL客户机(可视化)不支持多个语句,所以我不能在一开始就使用SET。有没有一种方法可以在不改变SQL输出的情况下将用户定义的变量包含到这样的语句中?
您可以在查询的任何地方使用@varname:='value'
。在这种情况下,您可以:
select A, B
from table1
JOIN (SELECT @x:='xxx') x
where C=@x
union select A, B from table2 where C=@x
union select A, B from table3 where C=@x
...
也可以再添加一个联合:
SELECT null,null FROM (SELECT @x:='xxx') x WHERE 0
union select A, B from table1 where C=@x
union select A, B from table2 where C=@x
union select A, B from table3 where C=@x
...
您可以将@x:='xxx'
放在任何方便的地方,只是要注意执行的顺序。