我有2-3个不同的列名,我想在整个数据库中查找,并列出所有具有这些列的表。有没有简单的脚本?


当前回答

SELECT DISTINCT TABLE_NAME, COLUMN_NAME  
FROM INFORMATION_SCHEMA.COLUMNS  
WHERE column_name LIKE 'employee%'  
AND TABLE_SCHEMA='YourDatabase'

其他回答

SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%wild%';

更简单地用一行SQL语句完成:

SELECT * FROM information_schema.columns WHERE column_name = 'column_name';
SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%city_id%' AND TABLE_SCHEMA='database'

information_schema的问题是它可能非常慢。使用SHOW命令速度更快。

选择数据库后,首先发送查询SHOW TABLES。然后对每个表执行SHOW COLUMNS。

在PHP中是这样的


    $res = mysqli_query("SHOW TABLES");
    while($row = mysqli_fetch_array($res))
    {   $rs2 = mysqli_query("SHOW COLUMNS FROM ".$row[0]);
        while($rw2 = mysqli_fetch_array($rs2))
        {   if($rw2[0] == $target)
               ....
        }
    }

如果你想“只获取所有的表”,那么使用这个查询:

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME like '%'
and TABLE_SCHEMA = 'tresbu_lk'

如果你想“获取所有带列的表”,那么使用这个查询:

SELECT DISTINCT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name LIKE '%'
AND TABLE_SCHEMA='tresbu_lk'