我试图使用一个选择语句从某个MySQL表中获得除一个以外的所有列。有什么简单的方法吗?
编辑:在这个表格中有53列(不是我的设计)
我试图使用一个选择语句从某个MySQL表中获得除一个以外的所有列。有什么简单的方法吗?
编辑:在这个表格中有53列(不是我的设计)
当前回答
如果你使用MySQL工作台,你可以右键单击你的表,点击发送到sql编辑器,然后选择所有语句,这将创建一个所有字段都被列出的语句,如下所示:
SELECT `purchase_history`.`id`,
`purchase_history`.`user_id`,
`purchase_history`.`deleted_at`
FROM `fs_normal_run_2`.`purchase_history`;
SELECT * FROM fs_normal_run_2.purchase_history;
现在你可以删除那些你不想要的。
其他回答
实际上有一种方法,当然你需要有权限才能这样做…
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 col1, col2, col3, col4 FROM tbl
并手动选择所需的列。然而,如果你想要很多列,那么你可能只需要做一个:
SELECT * FROM tbl
忽略你不想要的。
针对你的特殊情况,我建议:
SELECT * FROM tbl
除非你只想要几列。如果你只想要四列,那么:
SELECT col3, col6, col45, col 52 FROM tbl
这很好,但如果您想要50个列,那么任何使查询变得(太?)难以阅读的代码。
我有一个建议,但不是解决办法。 如果您的一些列有较大的数据集,那么您应该尝试使用以下方法
SELECT *, LEFT(col1, 0) AS col1, LEFT(col2, 0) as col2 FROM table
我也想要这个,所以我创建了一个函数。
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");
我很晚才想出一个答案,坦率地说,这是我一直在做的事情,它比最好的答案要好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]);