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

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


当前回答

在尝试@Mahomedalid和@Junaid的解决方案时,我发现了一个问题。所以我想分享一下。如果列名中有空格或连字符(如check-in),则查询将失败。简单的解决方法是在列名周围使用反标记。修改后的查询如下

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;

其他回答

起初我以为你可以使用正则表达式,但我一直在阅读MYSQL文档,似乎你不能。如果我是你,我会使用另一种语言(如PHP)来生成您想要获取的列的列表,将其存储为字符串,然后使用它来生成SQL。

是的,尽管根据表的不同,I/O可能会很高,但我找到了一个解决方案。

SELECT *
INTO #temp
FROM table

ALTER TABLE #temp DROP COlUMN column_name

SELECT *
FROM #temp

我很晚才想出一个答案,坦率地说,这是我一直在做的事情,它比最好的答案要好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]);

即使要查询所有列,也最好指定要查询的列。

因此,我建议您在语句中写下每一列的名称(不包括您不想要的列)。

SELECT
    col1
    , col2
    , col3
    , col..
    , col53

FROM table

我有一个建议,但不是解决办法。 如果您的一些列有较大的数据集,那么您应该尝试使用以下方法

SELECT *, LEFT(col1, 0) AS col1, LEFT(col2, 0) as col2 FROM table