MySql CLI - 查询的别名/名称

时间:2014-01-10 10:56:57

标签: mysql command-line-interface alias

有时我会编写跨越10行的复杂查询。然后我需要在其他复杂查询中的那些查询。是否可以为查询提供名称,只需在运行时通过实际查询替换该名称?

例如:

SET var_a = 'select f1, sum(f2) where .... (select .. from (select .. from))';
SET var_b = 'select g1, sum(g2) where .... (select .. from (select .. from))';

select z1, z2 from var_a union var_b;

mysql CLI可以像bash一样做一些简单的字符串替换吗?这样我就不需要为创建视图而烦恼了,只是为了在退出时清理它们。

2 个答案:

答案 0 :(得分:1)

我找到的关闭解决方案是:

SET @var_a = 'select f1, sum(f2) where .... (select .. from (select .. from))';
SET @var_b = 'select g1, sum(g2) where .... (select .. from (select .. from))';

SET @s = CONCAT('select ... from (', @var_a, ' union all ', @var_b, ')a');
PREPARE stmt FROM @s; EXECUTE stmt;

有点笨重但有效。

答案 1 :(得分:0)

您可以在SELECT语句中定义VIEW

CREATE VIEW var_a AS
  SELECT f1, SUM(f2) WHERE .... (SELECT .. FROM (SELECT .. FROM));

CREATE VIEW var_b AS
  SELECT g1, SUM(g2) WHERE .... (SELECT .. FROM (SELECT .. FROM));

然后将它们用作"表格"在后续查询中:

SELECT f1 FROM var_a UNION SELECT g1 FROM var_b