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

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


当前回答

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

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

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

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

其他回答

我的主要问题是在连接表时获得了许多列。虽然这不是您问题的答案(如何从一个表中选择除某些列之外的所有列),但我认为值得一提的是,您可以指定表。从特定表中获取所有列,而不是仅指定。

下面是一个很有用的例子:

select users.*, phone.meta_value as phone, zipcode.meta_value as zipcode

from users

left join user_meta as phone
on ( (users.user_id = phone.user_id) AND (phone.meta_key = 'phone') )

left join user_meta as zipcode
on ( (users.user_id = zipcode.user_id) AND (zipcode.meta_key = 'zipcode') )

结果是用户表中的所有列,以及从元表中连接的两个附加列。

我使用这个工作,尽管它可能是“离题”-使用mysql工作台和查询生成器-

打开列视图 Shift选择所有你想在你的查询列(在你的情况下,所有但这是我所做的) 右键单击并选择发送到SQL编辑器->名称短。 现在你有了列表,然后你可以复制粘贴查询到任何地方。

我也想要这个,所以我创建了一个函数。

public function getColsExcept($table,$remove){
    $res =mysql_query("SHOW COLUMNS FROM $table");

    while($arr = mysql_fetch_assoc($res)){
        $cols[] = $arr['Field'];
    }
    if(is_array($remove)){
        $newCols = array_diff($cols,$remove);
        return "`".implode("`,`",$newCols)."`";
    }else{
        $length = count($cols);
        for($i=0;$i<$length;$i++){
            if($cols[$i] == $remove)
                unset($cols[$i]);
        }
        return "`".implode("`,`",$cols)."`";
    }
}

所以它的工作原理是,你输入表格,然后是你不想要的列或在数组中:array("id","name","whatevercolumn")

所以在select中你可以这样使用它:

mysql_query("SELECT ".$db->getColsExcept('table',array('id','bigtextcolumn'))." FROM table");

or

mysql_query("SELECT ".$db->getColsExcept('table','bigtextcolumn')." FROM table");

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

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