我试图使用一个选择语句从某个MySQL表中获得除一个以外的所有列。有什么简单的方法吗?
编辑:在这个表格中有53列(不是我的设计)
我试图使用一个选择语句从某个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]);
其他回答
视图在这种情况下工作得更好吗?
CREATE VIEW vwTable
as
SELECT
col1
, col2
, col3
, col..
, col53
FROM table
据我所知,没有。你可以这样做:
SELECT col1, col2, col3, col4 FROM tbl
并手动选择所需的列。然而,如果你想要很多列,那么你可能只需要做一个:
SELECT * FROM tbl
忽略你不想要的。
针对你的特殊情况,我建议:
SELECT * FROM tbl
除非你只想要几列。如果你只想要四列,那么:
SELECT col3, col6, col45, col 52 FROM tbl
这很好,但如果您想要50个列,那么任何使查询变得(太?)难以阅读的代码。
如果你使用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;
现在你可以删除那些你不想要的。
是的,尽管根据表的不同,I/O可能会很高,但我找到了一个解决方案。
SELECT *
INTO #temp
FROM table
ALTER TABLE #temp DROP COlUMN column_name
SELECT *
FROM #temp
我同意列出所有列的“简单”解决方案,但这可能会造成负担,而且打字错误可能会浪费大量时间。我使用“getTableColumns”函数检索适合粘贴到查询中的列的名称。然后我要做的就是删除我不想要的。
CREATE FUNCTION `getTableColumns`(tablename varchar(100))
RETURNS varchar(5000) CHARSET latin1
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE res VARCHAR(5000) DEFAULT "";
DECLARE col VARCHAR(200);
DECLARE cur1 CURSOR FOR
select COLUMN_NAME from information_schema.columns
where TABLE_NAME=@table AND TABLE_SCHEMA="yourdatabase" ORDER BY ORDINAL_POSITION;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO col;
IF NOT done THEN
set res = CONCAT(res,IF(LENGTH(res)>0,",",""),col);
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
RETURN res;
您的结果返回一个以逗号分隔的字符串,例如…
col1, col2 col3 col4, ... col53