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

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


当前回答

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

其他回答

虽然我同意Thomas的答案(+1;)),但我想补充一点,即我假设您不想要的列几乎不包含任何数据。如果它包含大量的文本、xml或二进制blob,那么请花时间单独选择每一列。否则你的表现就会受到影响。干杯!

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

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

据我所知,没有。你可以这样做:

SELECT col1, col2, col3, col4 FROM tbl

并手动选择所需的列。然而,如果你想要很多列,那么你可能只需要做一个:

SELECT * FROM tbl 

忽略你不想要的。

针对你的特殊情况,我建议:

SELECT * FROM tbl

除非你只想要几列。如果你只想要四列,那么:

SELECT col3, col6, col45, col 52 FROM tbl

这很好,但如果您想要50个列,那么任何使查询变得(太?)难以阅读的代码。

如果愿意,可以使用SQL生成SQL,并对生成的SQL进行评估。这是一种通用的解决方案,因为它从信息模式中提取列名。下面是一个Unix命令行的示例。

替换

MYSQL的MYSQL命令 带有表名的TABLE 包含排除字段名的EXCLUDEDFIELD

echo $(echo 'select concat("select ", group_concat(column_name) , " from TABLE") from information_schema.columns where table_name="TABLE" and column_name != "EXCLUDEDFIELD" group by "t"' | MYSQL | tail -n 1) | MYSQL

实际上,您只需要以这种方式提取列名一次,就可以构造排除该列的列列表,然后只需使用已构造的查询。

比如:

column_list=$(echo 'select group_concat(column_name) from information_schema.columns where table_name="TABLE" and column_name != "EXCLUDEDFIELD" group by "t"' | MYSQL | tail -n 1)

现在可以在构造的查询中重用$column_list字符串。

如果你想排除一个字段的值,例如安全问题/敏感信息,你可以检索该列为空。

e.g.

SELECT *, NULL AS salary FROM users