php - 如何在php中编写复杂的mySQL select

标签 php mysql

我需要将以下 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/

相关文章:

MySQL 返回多行作为列

mysql - MS Access 表中列上的 md5 和 salt

php - 进入Fk表更新记录

PHP 在重命名之前检查文件是否打开

MySql 获取账户余额

javascript - Leaflet 每 5 秒从 MySQL 更新一次标记

javascript - highchart 通过在下拉列表中选择月份来更改图表

php - AJAX:跳转到由 PHP 使用 xmlhttp.open 动态创建的页面中的另一个部分(onClick() 是否在 href 之前运行?)

php - wp_enqueue_style 不添加版本

php - 使用 UNION 或以编程方式联合两个 MySQL 查询