Select all columns except one in MySQL?

后端 未结 30 2864
后悔当初
后悔当初 2020-11-22 00:46

I\'m trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this?

EDIT: There are 53 columns i

30条回答
  •  情歌与酒
    2020-11-22 01:28

    The accepted answer has several shortcomings.

    • It fails where the table or column names requires backticks
    • It fails if the column you want to omit is last in the list
    • It requires listing the table name twice (once for the select and another for the query text) which is redundant and unnecessary
    • It can potentially return column names in the wrong order

    All of these issues can be overcome by simply including backticks in the SEPARATOR for your GROUP_CONCAT and using a WHERE condition instead of REPLACE(). For my purposes (and I imagine many others') I wanted the column names returned in the same order that they appear in the table itself. To achieve this, here we use an explicit ORDER BY clause inside of the GROUP_CONCAT() function:

    SELECT CONCAT(
        'SELECT `',
        GROUP_CONCAT(COLUMN_NAME ORDER BY `ORDINAL_POSITION` SEPARATOR '`,`'),
        '` FROM `',
        `TABLE_SCHEMA`,
        '`.`',
        TABLE_NAME,
        '`;'
    )
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE `TABLE_SCHEMA` = 'my_database'
        AND `TABLE_NAME` = 'my_table'
        AND `COLUMN_NAME` != 'column_to_omit';
    

提交回复
热议问题