1

我在 Workbench 中创建了 MySQL 查询插值。该查询非常适合我的需求,只是我无法将“用户定义的变量”@var1/2/3 作为我的字段别名。

我在这一行中遇到AS @var1(SELECT field4 FROM view_table LIMIT 0, 1) AS @var1错误,我怀疑字段 Alias 不接受“用户定义的变量”,如下面的 MySQL 查询所示:

DROP VIEW IF EXISTS view_table;

CREATE VIEW view_table AS
     SELECT table3.field1, table1.field2
     FROM table1
     JOIN table2 ON table1.table2_id = table2.id
     JOIN table3 ON table1.table3_id = table3.id
     JOIN table4 ON item_var.table4_id = table4.id
     WHERE table2.id = 1
     ORDER BY table1 ASC LIMIT 3;

SET @var1 := (SELECT table3.field1 FROM view_table LIMIT 0, 1);  -- created for the @var1 variable
SET @var2 := (SELECT table3.field1 FROM view_table LIMIT 1, 1);  -- created for the @var2 variable
SET @var3 := (SELECT table3.field1 FROM view_table LIMIT 2, 1);  -- created for the @var3 variable

SELECT table4.field1, table2.field2, table2.field3,
     (SELECT field4 FROM view_table LIMIT 0, 1) AS @var1,  -- @var1 is not recognized as alias
     (SELECT field5 FROM view_table LIMIT 1, 1) AS @var2,  -- @var2 is not recognized as alias
     (SELECT field6 FROM view_table LIMIT 2, 1) AS @var3   -- @var3 is not recognized as alias
FROM table2
JOIN table4 ON table2.id = table4.id
WHERE table2.id = 1;

这是我想要的查询结果:

+-------------+------------+------------+------------+------------+-------------+------------+
|name         |Field1      |Field2      |Field3      |@var1       |@var2        |@var3       |
+-------------+------------+------------+------------+------------+-------------+------------+
|XYZ Company  |Field1Data  |Field2Data  |Field3Data  |Field4Data  | Field5Data  |Field6Data  |
+-------------+------------+------------+------------+------------+------------+-------------+

任何人都可以帮我找出作为字段别名的标头变量的正确 MySQL 语法吗?

更新: 我已经发布了下面的解决方案以供参考。

4

1 回答 1

0

最后!我得到了解决方案!

我只需要将上面的最后一个查询连接起来,就可以插入我创建的字段变量。然后,将它传递给一个语句,执行该语句并释放它以释放它。

SET @statement_var = CONCAT("
SELECT table4.field1, table2.field2, table2.field3, 
    (SELECT field4 FROM view_table LIMIT 0, 1) AS '", @var1, "' ,   
    (SELECT field5 FROM view_table LIMIT 1, 1) AS '", @var1, "' , 
    (SELECT field6 FROM view_table LIMIT 2, 1) AS '", @var1, "' 
FROM table2
JOIN table4 ON item_table2.id = table4.id
WHERE table2.id = 1;");

PREPARE statement FROM @statement_var;

EXECUTE statement;

DEALLOCATE PREPARE statement;

希望这对其他有插值问题的人有所帮助。干杯!

于 2020-06-28T00:50:18.027 回答