我在 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 语法吗?
更新: 我已经发布了下面的解决方案以供参考。