我有一个相对较长的联合选择:
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输出的情况下将用户定义的变量包含在这样的语句中?
发布于 2021-03-29 23:12:08
您几乎可以在查询中的任何地方使用@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'放在任何方便的地方,只要注意执行的顺序即可。
https://stackoverflow.com/questions/66856516
复制相似问题