Mysql:在 select 语句中创建内联表?

标签 mysql sql

有没有办法在 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/

相关文章:

javascript - 用户点击搜索按钮后 map 不显示错误在哪里?

mysql - 从通过匹配 SQL 中的正则表达式生成的列中获取唯一条目

sql - sql的UNION子句性能问题

sql - 有没有更好的方法来完成这个sql查询?

android - SQLite 查询 : selecting the newest row for each distinct contact

mysql - SSIS ODBC 源未在 SQL Server 代理作业中保存密码

mysql - MySQL如何决定它是否使用GROUP BY的索引?

MySQL - INSERT INTO table SELECT WHERE field IN(子查询) - 使用 IN 使事情变得非常慢,正确的方法是吗?

sql - 为什么 wm_concat 在这里不起作用?

sql - 使用 TSQL,如何判断我的 CHAR 是否是序列中的最后一个?另外,如果字母序列 "rolls over"从 'z' 到 'a' 怎么办?