我有几个(相当标准的)(MySQL)查询,如下所示:
select *
from table_one a
left join table_two on a.id = b.id
left join table_three c on b.id = c.id.
table_one看起来像这样:
id (int)
label (varchar(15)
table_two看起来像这样:
id (int)
name (varchar(20)
table_three看起来像这样:
id (int)
some_field_name (varchar(25)
结果就是这样:
id|label|id|name|id|some_field_name|
..|.....|..|....|..|...............|
现在,我想要的是一个列表,其中包含他的查询将产生的列名(最好还有列名)
像这样
id(int)
label (varchar(15)
id (int)
name varchar(20)
id (int)
some_field_name (varchar(25)
我知道我可以使用INFORMATION_SCHEMA.COLUMNS表获取此信息,但是随后我仍然必须手动为每个表运行此查询,并自己“组成”每个查询的列表。
我希望我可以提供一个查询,然后返回字段名+字段类型列表的函数。
答案 0 :(得分:1)
我们在php中有$ stmt-> getColumnMeta()来获取列的元数据
<?php
$user = 'root';
$pass = 'infiniti';
$DB = 'test';
$host = 'localhost';
$c = new \PDO('mysql:host='.$host.';dbname='.$DB, $user, $pass);
$c->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$dataQuery = 'select * from info limit 3';
$stmt = $c->prepare($dataQuery);
$stmt->execute();
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
echo $stmt->columnCount();
for($i = 0; $i < $stmt->columnCount(); $i++)
{
print_r($stmt->getColumnMeta($i));
}
output
Array
(
[native_type] => LONG
[pdo_type] => 2
[flags] => Array
(
[0] => not_null
[1] => primary_key
)
[table] => info
[name] => id
[len] => 11
[precision] => 0
)
Array
(
[native_type] => VAR_STRING
[pdo_type] => 2
[flags] => Array
(
)
[table] => info
[name] => fname
[len] => 60
[precision] => 0
)
Array
(
[native_type] => VAR_STRING
[pdo_type] => 2
[flags] => Array
(
)
[table] => info
[name] => lname
[len] => 60
[precision] => 0
)
答案 1 :(得分:0)
I guess only the data of the column (not the data type and data length) will be returned to any scripting language.
if it takes long time to get datatype of col's used in queries, you could retrieve all col's datatype and store it in a variable, or in a CSV.
This will work as long as you have few tables with minimum columns.
select
COLUMN_NAME
DATA_TYPE
from
information_schema.columns c
where
c.TABLE_SCHEMA = 'DATABASE_NAME';