SQL:查询数据库中所有表的字段,并在查询结果中返回表、字段、字段描述。

问题描述 投票:0回答:1

这是我的第一个堆栈溢出问题。

我试图查询一个包含多个表的MySQL数据库中是否存在一个特定字段。不幸的是,我正在处理一个数据库,不同的字段值可能意味着不同的事情。

这部分是好的,但我还需要在查询结果中返回表名。表的数量越来越多。这就是我被卡住的部分。

这是我试过的。

    SELECT table_name FROM information_schema.tables
    WHERE table_schema = 'test_db'
            SELECT IF( EXISTS(
                 SELECT col_name, description
                 FROM table_name
                 WHERE col_name = field_value)) ;

我的逻辑(如果有缺陷,请协助,我是来学习的!)。

  1. 第一个查询选择数据库中的所有表进行查询。
  2. 子查询只返回那些有我要搜索的字段的表,以及它们的描述。

我希望我的结果看起来像这样。

------------------------------------------------
             query results
------------------------------------------------
table_name | query_field_val | field_description
-------------------------------------------------
table1     | foo             | foo is foo
-------------------------------------------------
table2     | foo             | foo is not bar
-------------------------------------------------
table3     | foo             | foo is in foobar    

下面是一个表结构的例子(表的数量越来越多,所以如果可能的话,我希望不要硬编码表名)每个表都是不同数据库中另一个表的结果。它包含所有的列值和描述。描述与模式无关,它只是一个字符串。

---------------------------
          table_1
---------------------------
   col_values | desc
---------------------------
 foo          | foo foo foo
---------------------------
 bar          | bar bar bar
---------------------------
 foobar       | foobar foo

          table_2
---------------------------
   col_values | desc
---------------------------
 foo          | not bar
---------------------------
 foobar       | bar in bar

有没有更好的方法?

希望能描述的够清楚! 谢谢你看一下。

mysql database database-design mysql-python
1个回答
0
投票

试试这个。

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA='test_db' AND column_name = 'col_name';
© www.soinside.com 2019 - 2024. All rights reserved.