Select all columns except one in MySQL?

后端 未结 30 2846
后悔当初
后悔当初 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:11

    If the column that you didn't want to select had a massive amount of data in it, and you didn't want to include it due to speed issues and you select the other columns often, I would suggest that you create a new table with the one field that you don't usually select with a key to the original table and remove the field from the original table. Join the tables when that extra field is actually required.

    0 讨论(0)
  • 2020-11-22 01:12

    Actually there is a way, you need to have permissions of course for doing this ...

    SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');
    
    PREPARE stmt1 FROM @sql;
    EXECUTE stmt1;
    

    Replacing <table>, <database> and <columns_to_omit>

    0 讨论(0)
  • 2020-11-22 01:13

    While trying the solutions by @Mahomedalid and @Junaid I found a problem. So thought of sharing it. If the column name is having spaces or hyphens like check-in then the query will fail. The simple workaround is to use backtick around column names. The modified query is below

    SET @SQL = CONCAT('SELECT ', (SELECT GROUP_CONCAT(CONCAT("`", COLUMN_NAME, "`")) FROM
    INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users' AND COLUMN_NAME NOT IN ('id')), ' FROM users');
    PREPARE stmt1 FROM @SQL;
    EXECUTE stmt1;
    
    0 讨论(0)
  • 2020-11-22 01:15

    Would a View work better in this case?

    CREATE VIEW vwTable
    as  
    SELECT  
        col1  
        , col2  
        , col3  
        , col..  
        , col53  
    FROM table
    
    0 讨论(0)
  • 2020-11-22 01:15

    If it's always the same one column, then you can create a view that doesn't have it in it.

    Otherwise, no I don't think so.

    0 讨论(0)
  • 2020-11-22 01:16

    In mysql definitions (manual) there is no such thing. But if you have a really big number of columns col1, ..., col100, the following can be useful:

    DROP TABLE IF EXISTS temp_tb;
    CREATE TEMPORARY TABLE ENGINE=MEMORY temp_tb SELECT * FROM orig_tb;
    ALTER TABLE temp_tb DROP col_x;
       #// ALTER TABLE temp_tb DROP col_a, ... , DROP col_z; #// for a few columns to drop
    SELECT * FROM temp_tb;
    
    0 讨论(0)
提交回复
热议问题