如何从 SELECT 查询(而不是表)显示列?

发布于 2024-09-19 13:31:21 字数 142 浏览 5 评论 0原文

运行以下命令时出现语法错误:

show columns from (select * from (select * from my_table) as T)

如何显示我编写的查询中的列,而不是表中的列?

I get a syntax error when I run the following:

show columns from (select * from (select * from my_table) as T)

How can I show the columns from a query that I wrote, rather than from a table?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

初见 2024-09-26 13:31:21

方法 1:临时表

已经发布的有关使用临时表的答案通常是最合适的解决方案。但有一点很重要,如果查询按原样运行,所有连接等都将被处理,在某些情况下这可能需要很长时间。幸运的是,MySQL 允许 LIMIT 0 不返回任何行,并且 文档指出这“快速返回一个空集”。以下存储过程将为您完成这项工作,方法是将 SQL 查询字符串作为输入,用 LIMIT 0 包装它,运行动态查询以生成临时表,然后显示其列:

CREATE PROCEDURE showColumns(IN sqlToShow TEXT)
BEGIN
    DROP TEMPORARY TABLE IF EXISTS tempTable;
    SET @sqlLimit0 = CONCAT('CREATE TEMPORARY TABLE tempTable AS (SELECT * FROM (',
                            sqlToShow, ') subq LIMIT 0)');
    PREPARE stmt FROM @sqlLimit0;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    SHOW COLUMNS FROM tempTable;
END;

一个重要点传入的查询末尾不应有分号。 (如有必要,可以修改存储过程以删除尾随分号,但我想保持简单。)

这是一个实时演示,展示了它的实际效果:http://rextester.com/NVWY58430

方法 2:INFORMATION_SCHEMA.COLUMNS

SHOW COLUMNS< 返回的信息相同/code> 也可以直接从 INFORMATION_SCHEMA 获取。 COLUMNS 表:

SELECT TABLE_NAME AS `Table`,
       COLUMN_NAME AS `Field`,
       COLUMN_TYPE AS `Type`,
       IS_NULLABLE AS `Null`,
       COLUMN_KEY AS `Key`, 
       COLUMN_DEFAULT AS `Default`,
       EXTRA AS `Extra`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA` = SCHEMA() -- This uses the current schema
  AND `TABLE_NAME` IN ('table1', 'table2', 'etc.');
   -- ...or could go even further and restrict to particular columns in tables if desired

上面的缺点是需要手动输入表(和可选的列)名称并且不在 SELECT 中显示别名,但它确实基本工作。它的优点是不需要用户拥有创建临时表的权限,并且返回的信息可以扩展以提供进一步的列信息,例如最大字符长度、数字精度/小数位数、列注释等。

METHOD 1: Temporary table

The answers already posted about using a temporary table will usually be the most appropriate solution. But there is an important point that if the query is run as-is, all the joins etc. will be processed, which could potentially take a long time in some cases. Fortunately, MySQL allows LIMIT 0 to return no rows and the documentation states that this "quickly returns an empty set". The following stored procedure will do this job for you by taking a SQL query string as input, wrapping it with LIMIT 0, running the dynamic query to produce a temporary table and then showing its columns:

CREATE PROCEDURE showColumns(IN sqlToShow TEXT)
BEGIN
    DROP TEMPORARY TABLE IF EXISTS tempTable;
    SET @sqlLimit0 = CONCAT('CREATE TEMPORARY TABLE tempTable AS (SELECT * FROM (',
                            sqlToShow, ') subq LIMIT 0)');
    PREPARE stmt FROM @sqlLimit0;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    SHOW COLUMNS FROM tempTable;
END;

One important point is the query passed in should not have a semi-colon at the end. (If necessary, the stored procedure could be modified to remove trailing semi-colons but I wanted to keep it simple.)

Here is a live demo showing it in action: http://rextester.com/NVWY58430

METHOD 2: INFORMATION_SCHEMA.COLUMNS

The same information returned by SHOW COLUMNS can also be obtained directly from the INFORMATION_SCHEMA.COLUMNS table:

SELECT TABLE_NAME AS `Table`,
       COLUMN_NAME AS `Field`,
       COLUMN_TYPE AS `Type`,
       IS_NULLABLE AS `Null`,
       COLUMN_KEY AS `Key`, 
       COLUMN_DEFAULT AS `Default`,
       EXTRA AS `Extra`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA` = SCHEMA() -- This uses the current schema
  AND `TABLE_NAME` IN ('table1', 'table2', 'etc.');
   -- ...or could go even further and restrict to particular columns in tables if desired

The above suffers from the disadvantages of requiring the table (and optionally column) names to be entered manually and not showing alias names in the SELECT but it does the basic job. Its advantages are it doesn't require the user to have permission to create a temporary table and the information returned could be extended to provide further column information such as maximum character length, numeric precision/scale, column comments etc.

千纸鹤带着心事 2024-09-26 13:31:21

我正在使用 Java 从 MySql 查询中检索列。

在 Java 中获取结果集的列信息的最佳方法是使用 ResultSetMetaData 接口:

PreparedStatement stmt = null;
ResultSet result = null;
ResultSetMetaData meta = null;

try {
    stmt = con.prepareStatement("SELECT * FROM MyTable"); 
    result = stmt.executeQuery();
} catch (SQLException e) {
    System.out.println("SQLException: "+e.getMessage());
    System.exit(1);
}
System.out.println("Successful query");

try {
    meta = result.getMetaData();
    System.out.println("Total columns: " + meta.getColumnCount());
    System.out.println("Name of column 1: " + meta.getColumnName(1));
    System.out.println("Type of column 1: " + meta.getColumnTypeName(1));

    System.out.println("Name of column 2: " + meta.getColumnName(2));
    System.out.println("Type of column 2: " + meta.getColumnTypeName(2));
} catch (SQLException e) {
    System.out.println("SQLException: "+e.getMessage());
    System.exit(1);
}
System.out.println("Successful metadata report");

我的表已声明:

CREATE TABLE `MyTable` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

我的示例 Java 代码的输出:

Successful query
Total columns: 2
Name of column 1: id
Type of column 1: BIGINT UNSIGNED
Name of column 2: name
Type of column 2: VARCHAR
Successful metadata report

除了结果集列之外,您还可以获得有关结果集列的其他信息名称和数据类型。请参阅 http://docs.oracle.com/javase/ 8/docs/api/java/sql/ResultSetMetaData.html 有关 ResultSetMetaData 接口的完整参考文档。

I am using Java to retrieve columns from MySql query.

The best way in Java to get column information for a result set is to use the ResultSetMetaData interface:

PreparedStatement stmt = null;
ResultSet result = null;
ResultSetMetaData meta = null;

try {
    stmt = con.prepareStatement("SELECT * FROM MyTable"); 
    result = stmt.executeQuery();
} catch (SQLException e) {
    System.out.println("SQLException: "+e.getMessage());
    System.exit(1);
}
System.out.println("Successful query");

try {
    meta = result.getMetaData();
    System.out.println("Total columns: " + meta.getColumnCount());
    System.out.println("Name of column 1: " + meta.getColumnName(1));
    System.out.println("Type of column 1: " + meta.getColumnTypeName(1));

    System.out.println("Name of column 2: " + meta.getColumnName(2));
    System.out.println("Type of column 2: " + meta.getColumnTypeName(2));
} catch (SQLException e) {
    System.out.println("SQLException: "+e.getMessage());
    System.exit(1);
}
System.out.println("Successful metadata report");

My table is declared:

CREATE TABLE `MyTable` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

Output of my example Java code:

Successful query
Total columns: 2
Name of column 1: id
Type of column 1: BIGINT UNSIGNED
Name of column 2: name
Type of column 2: VARCHAR
Successful metadata report

You can get other information about result set columns besides their names and data types. See http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSetMetaData.html for full reference docs on the ResultSetMetaData interface.

梦太阳 2024-09-26 13:31:21

看起来这个语句只接受现有的表。

因此,我使用查询创建了一个新的临时表,并从那里获取了列名称。

/*if the exporting table was created before, then delete it*/
DROP TABLE IF EXISTS exportTable;

/*create the temporary table (check if you have mySQL permission to do so)*/
CREATE TEMPORARY TABLE exportTable AS (your_query);

/*get result table (this is a table, the columns names are in the first column of this table ['Field'])*/
SHOW COLUMNS FROM exportTable;

临时表在会话上下文中创建,并在会话关闭时删除。 SHOW COLUMNS 表也是如此。您可能会考虑这些表创建对服务器磁盘的影响。

创建表时可以使用 TEMPORARY 关键字。 临时表仅对当前会话可见,并在会话关闭时自动删除。这意味着两个不同的会话可以使用相同的临时表名称,而不会相互冲突或与现有的临时表发生冲突。同名的非 TEMPORARY 表。 (现有表将被隐藏,直到删除临时表。)要创建临时表,您必须具有 CREATE TEMPORARY TABLES 权限。

http://dev.mysql.com/doc/refman/5.7 /en/create-table.html

Looks like this statement only accepts existing tables.

So I created a new temporary table with my query and got the column names from there.

/*if the exporting table was created before, then delete it*/
DROP TABLE IF EXISTS exportTable;

/*create the temporary table (check if you have mySQL permission to do so)*/
CREATE TEMPORARY TABLE exportTable AS (your_query);

/*get result table (this is a table, the columns names are in the first column of this table ['Field'])*/
SHOW COLUMNS FROM exportTable;

The temporary table is created in session context, and will be droped when session is closed. The same is for the SHOW COLUMNS table. You might consider the impact of these table creations on the server disk.

You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.) To create temporary tables, you must have the CREATE TEMPORARY TABLES privilege.

http://dev.mysql.com/doc/refman/5.7/en/create-table.html

你爱我像她 2024-09-26 13:31:21

我用这样的东西:

create procedure showFields(s text)
begin
set @showfields_var:=concat('create temporary table tmp_showfields as select * from (',s,')a where 0'); 
prepare phrase from @showfields_var;execute phrase;
show columns from tmp_showfields;
drop temporary table tmp_showfields;
end

I use something like this:

create procedure showFields(s text)
begin
set @showfields_var:=concat('create temporary table tmp_showfields as select * from (',s,')a where 0'); 
prepare phrase from @showfields_var;execute phrase;
show columns from tmp_showfields;
drop temporary table tmp_showfields;
end
明月夜 2024-09-26 13:31:21

试试这个 -

SHOW COLUMNS FROM (select * from my_table) T

或直接SHOW COLUMNS FROM my_table

try this -

SHOW COLUMNS FROM (select * from my_table) T

or Directly SHOW COLUMNS FROM my_table

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文