[英]MySQL query within a query
So I am trying to write a query where I get the column information from a query this is what i tried: 所以我试图写一个查询,我从查询中获取列信息,这就是我尝试过的:
Select login from TableName AS alias_name
SELECT COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,IS_NULLABLE,COLUMN_DEFAULT,
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_Name = 'alias_name' ORDER BY ORDINAL_POSITION ASC;
... this doesn't work because the query is not saved as a temporary table or what not ... ...这不起作用,因为查询未保存为临时表或其他不保存的信息...
so I need the functionally of the two queries above combined into one query thanks 所以我需要将以上两个查询的功能组合成一个查询,谢谢
Try this: 尝试这个:
SELECT COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,IS_NULLABLE,COLUMN_DEFAULT,
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_Name IN (SELECT login from TableName)
ORDER BY ORDINAL_POSITION ASC;
Is that what you are trying to do? 那是你想做的吗?
This is not possible; 这是不可能的; not in pure SQL.
不是纯SQL。 This is not a property of MySQL - other RDBMS-es also do not offer query metadata in this way.
这不是MySQL的属性-其他RDBMS-es也不以这种方式提供查询元数据。
The closest you can get to solving this in pure SQL is to turn your query into a view, and then get the info for that view: 使用纯SQL解决此问题的最接近方法是将查询转换为视图,然后获取该视图的信息:
CREATE OR REPLACE VIEW _query
AS
SELECT login
FROM TableName
;
SELECT *
FROM information_schema.COLUMNS
WHERE table_schema = SCHEMA()
AND table_name = '_query'
;
The problem with this approach is that view names have to be unique, so an application with multiple concurrent users has the challenge to come up with a unique name for the view. 这种方法的问题在于视图名称必须唯一,因此具有多个并发用户的应用程序要为视图提供唯一名称是一个挑战。 This is possible using dynamic sql:
使用动态sql可以实现:
SET @name = CONCAT(_query, connection_id())
, @stmt = CONCAT(
' CREATE VIEW '
, @name
, ' AS SELECT login FROM Tablename'
)
;
PREPARE stmt FROM @stmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SELECT *
FROM information_schema.columns
WHERE table_schema = schema()
AND table_name = @name
;
Finally, you should probably clean up your view afterwards: 最后,您可能应该在之后清理视图:
SET @stmt = CONCAT('DROP VIEW ', @name);
PREPARE stmt FROM @stmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
The question is, why do you need this inside SQL? 问题是,为什么在SQL中需要这个? Typically, resultset metadata is available in SQL clients - typically the driver or client library provides this as you prepare a SQL statement.
通常,结果集元数据在SQL客户端中可用-通常,驱动程序或客户端库在准备SQL语句时会提供此结果。 For instance in JDBC http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getMetaData ()
例如在JDBC http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getMetaData ()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.