简体   繁体   English

mysql:检查一个查询中是否存在表和列?

[英]mysql: check if table(s) AND column(s) exist in ONE query?

Working with multiple tables, the task is to check if the table exists and its certain columns exist, too. 使用多个表时,任务是检查表是否存在以及其某些列是否也存在。

The query 查询

SELECT
    (TABLE_NAME) AS table_name,
    (GROUP_CONCAT(COLUMN_NAME)) AS column_name
FROM information_schema.COLUMNS
WHERE
    TABLE_SCHEMA = 'dbms'
AND
    TABLE_NAME IN ('user', 'status')
AND
    COLUMN_NAME IN ('id', 'name')
GROUP BY table_name

works fine to detect existing columns, but returns nothing if either table does not exist or none of the columns exist. 可以很好地检测现有的列,但是如果其中一个表不存在或不存在任何列,则不返回任何内容。 The latter should be differentiated. 后者应加以区分。 How to? 如何? How to know whether it's a table or column names that do not exist? 如何知道它是不存在的表名还是列名?

To clarify, the query above will return 2 rows by 2 columns: 为了澄清,上面的查询将返回2行乘2列:

user   | id, name
status | id, name

means, each table has both of the columns. 意味着,每个表都有两列。

Changing one column name to, say, name1, will result in: 将一个列名更改为name1将导致:

user   | id
status | id

means, only id exists. 表示仅存在id。

Changing column names to name1, id1 will return nothing. 将列名更改为name1,id1将不返回任何内容。 This is the problem. 这就是问题。 It is impossible to say whether tables do not exist or columns. 不能说表是不存在还是列。

It would be good if the return would look something like: 如果收益看起来像这样会很好:

user   | ''
status | ''

and if, say status does not exist, then like: 如果说状态不存在,则类似于:

user   | ''

what can be decoded as only user table exists, and none of the columns named in it. 可以解码为仅用户表的内容,并且其中没有命名的列。

You cannot use WHERE for column_name is you still want rows in the result set even if they don't match. 您不能对列名使用WHERE ,因为即使它们不匹配,您仍然希望结果集中的行。 It looks like the only real WHERE clause you want is based on the table name, and the column name is simply a display condition. 看起来您想要的唯一真正的WHERE子句是基于表名的,而列名只是显示条件。

SELECT
    table_name
    GROUP_CONCAT(IF(column_name IN ('id','name'), column_name, NULL))
FROM information_schema.columns
WHERE table_schema = 'dbms'
AND table_name IN ('user','status')
GROUP BY table_name

you just need to change your logic in and condition as mentioned in your query TABLE_SCHEMA = 'dbms' AND TABLE_NAME IN ('user', 'status') AND COLUMN_NAME IN ('id', 'name') 您只需要更改查询中提到的逻辑和条件TABLE_SCHEMA ='dbms'AND TABLE_NAME IN('user','status')AND COLUMN_NAME IN('id','name')

it will fetch only the resultset if there are tables users or status with column name id or name in dbms, what you can do is separately check for tables and if table exist check for columns. 如果存在表名称为dbms或列名称为dbms的表用户或状态,它将仅获取结果集,您可以做的是分别检查表以及表是否存在以检查列。 I hope it would help 我希望这会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM