有没有办法在 MySql 中创建一个用于连接的内联表?
类似:
SELECT LONG [1,2,3] as ID, VARCHAR(1) ['a','b','c'] as CONTENT
那会输出
| ID | CONTENT |
| LONG | VARCHAR(1)|
+------+-----------+
| 1 | 'a' |
| 2 | 'b' |
| 3 | 'c' |
我可以像这样在连接中使用:
SELECT
MyTable.*,
MyInlineTable.CONTENT
FROM
MyTable
JOIN
(SELECT LONG [1,2,3] as ID, VARCHAR(1) ['a','b','c'] as CONTENT MyInlineTable)
ON MyTable.ID = MyInlineTable.ID
我意识到我可以做到
SELECT 1,'a' UNION SELECT 2,'b' UNION SELECT 3,'c'
但这看起来很邪恶
我不想执行存储过程,因为 a、b、c 可能会在每次查询和数据大小时发生变化。还需要将存储过程保存在数据库中,我不想为此修改数据库。 View 是一样的。
我真正想要的是用更好的语法来执行 SELECT 1,'a' UNION SELECT 2,'b' UNION SELECT 3,'c'
的东西。
最佳答案
我现在能记住的唯一方法是使用 UNION
或创建一个 TEMPORARY TABLE
并将这些值插入其中。适合你吗?
TEMPORARY_TABLE
(经过测试并且有效):
创作:
CREATE TEMPORARY TABLE MyInlineTable (id LONG, content VARCHAR(1) );
INSERT INTO MyInlineTable VALUES
(1, 'a'),
(2, 'b'),
(3, 'c');
用法:
SELECT
MyTable.*,
MyInlineTable.CONTENT
FROM
MyTable
JOIN
SELECT * FROM MyInlineTable;
ON MyTable.ID = MyInlineTable.ID
TEMPORARY_TABLES
生命周期 (reference) :
Temporary tables are automatically dropped when they go out of scope, unless they have already been explicitly dropped using DROP TABLE:
.
All other local temporary tables are dropped automatically at the end of the current session.
.
Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended.`
关于Mysql:在 select 语句中创建内联表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9520442/