Select all columns except one in MySQL?

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

    I wanted this too so I created a function instead.

    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)."`";
        }
    }
    

    So how it works is that you enter the table, then a column you don't want or as in an array: array("id","name","whatevercolumn")

    So in select you could use it like this:

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

    or

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

提交回复
热议问题