我需要将以下 mySQL 查询写入我需要为多个模式执行的 PHP 格式。此查询生成一个数据字典。
select t.table_schema as schema_name,
t.table_name,
(case when t.table_type = 'BASE TABLE' then 'table'
when t.table_type = 'VIEW' then 'view'
else t.table_type end) as table_type,
c.column_name,
c.column_type,
c.column_default,
(case when c.column_key = ' ' then '-'
when c.column_key = 'MUL' then 'FK'
else 'PK' end) as column_key,
c.is_nullable,
c.column_comment
from information_schema.tables as t
inner join information_schema.columns as c on t.table_name = c.table_name and t.table_schema = c.table_schema
where t.table_type in('base table', 'view') and t.table_schema = 'testdb'
order by t.table_schema, t.table_name, c.ordinal_position
我尝试在 PHP 中使用以下语法:
$sql = "select t.table_schema as schema_name,
t.table_name,
(case when t.table_type = 'BASE TABLE' then 'table'
when t.table_type = 'VIEW' then 'view'
else t.table_type end) as table_type,
c.column_name,
c.column_type,
c.column_default,
(case when c.column_key = ' ' then '-'
when c.column_key = 'MUL' then 'FK'
else 'PK' end) as column_key,
c.is_nullable,
c.column_comment
from information_schema.tables as t
inner join information_schema.columns as c on t.table_name = c.table_name and t.table_schema = c.table_schema
where t.table_type in('base table', 'view') and t.table_schema = 'testdb'
order by t.table_schema, t.table_name, c.ordinal_position";
但是当我执行此操作时,出现以下错误:
Notice: Undefined index: t.table_schema in C:\laragon\www\createDict.php on line 32
schema_name:
我用它来创建输出(现在只是第一列):
while($row = $result->fetch_assoc())
{
echo "schema_name: " . $row["t.table_schema"]."<br>";
}
如果有人能帮助我,我将不胜感激。感谢您的宝贵时间!
最佳答案
在您的查询中您有:
select t.table_schema as schema_name
因此,一旦您在 PHP 中返回结果,包含数据的数组将调用此“schema_name”。你应该使用:
echo "schema_name: " . $row["schema_name"]."<br>";
旁注:PHP 中的结果数组不包含数据中的表名,因此在选择 c.column_type
的地方,您需要使用 $row 获取值['column_type']
-- 没有 c.
部分。
关于php - 如何在php中编写复杂的mySQL select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44461993/