我试图使用一个选择语句从某个MySQL表中获得除一个以外的所有列。有什么简单的方法吗?

编辑:在这个表格中有53列(不是我的设计)


当前回答

实际上有一种方法,当然你需要有权限才能这样做…

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;

替换<表>,<数据库>和< columns_to_省略>

其他回答

你可以:

SELECT column1, column2, column4 FROM table WHERE whatever

没有得到列3,尽管您可能在寻找一个更一般的解?

如果您不想选择的列中有大量数据,并且由于速度问题而不想包括它,并且您经常选择其他列,那么我建议您使用一个通常不选择的字段创建一个新表,并从原始表中删除该字段。当实际需要额外字段时,将表连接起来。

我想添加另一个观点来解决这个问题,特别是如果你有少量的列要删除。

您可以使用像MySQL Workbench这样的DB工具来为您生成选择语句,因此您只需手动删除生成语句的那些列,并将其复制到SQL脚本中。

在MySQL Workbench中,生成它的方法是:

右键单击表->发送到Sql编辑器->选择所有语句。

我很晚才想出一个答案,坦率地说,这是我一直在做的事情,它比最好的答案要好100倍,我只希望有人能看到它。发现它很有用

    //create an array, we will call it here. 
    $here = array();
    //create an SQL query in order to get all of the column names
    $SQL = "SHOW COLUMNS FROM Table";
        //put all of the column names in the array
        foreach($conn->query($SQL) as $row) {
            $here[] = $row[0];
        }
    //now search through the array containing the column names for the name of the column, in this case i used the common ID field as an example
    $key = array_search('ID', $here);
    //now delete the entry
    unset($here[$key]);

实际上有一种方法,当然你需要有权限才能这样做…

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;

替换<表>,<数据库>和< columns_to_省略>