我试图使用一个选择语句从某个MySQL表中获得除一个以外的所有列。有什么简单的方法吗?
编辑:在这个表格中有53列(不是我的设计)
我试图使用一个选择语句从某个MySQL表中获得除一个以外的所有列。有什么简单的方法吗?
编辑:在这个表格中有53列(不是我的设计)
当前回答
据我所知,没有。你可以这样做:
SELECT col1, col2, col3, col4 FROM tbl
并手动选择所需的列。然而,如果你想要很多列,那么你可能只需要做一个:
SELECT * FROM tbl
忽略你不想要的。
针对你的特殊情况,我建议:
SELECT * FROM tbl
除非你只想要几列。如果你只想要四列,那么:
SELECT col3, col6, col45, col 52 FROM tbl
这很好,但如果您想要50个列,那么任何使查询变得(太?)难以阅读的代码。
其他回答
我很晚才想出一个答案,坦率地说,这是我一直在做的事情,它比最好的答案要好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]);
据我所知,没有。你可以这样做:
SELECT col1, col2, col3, col4 FROM tbl
并手动选择所需的列。然而,如果你想要很多列,那么你可能只需要做一个:
SELECT * FROM tbl
忽略你不想要的。
针对你的特殊情况,我建议:
SELECT * FROM tbl
除非你只想要几列。如果你只想要四列,那么:
SELECT col3, col6, col45, col 52 FROM tbl
这很好,但如果您想要50个列,那么任何使查询变得(太?)难以阅读的代码。
也许我有一个解决Jan Koritak指出的矛盾的方法
SELECT CONCAT('SELECT ',
( SELECT GROUP_CONCAT(t.col)
FROM
(
SELECT CASE
WHEN COLUMN_NAME = 'eid' THEN NULL
ELSE COLUMN_NAME
END AS col
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test'
) t
WHERE t.col IS NOT NULL) ,
' FROM employee' );
表:
SELECT table_name,column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test'
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
table_name column_name
employee eid
employee name_eid
employee sal
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
查询结果:
'SELECT name_eid,sal FROM employee'
基于@Mahomedalid的答案,我做了一些改进,以支持“选择mysql中除某些列外的所有列”
SET @database = 'database_name';
SET @tablename = 'table_name';
SET @cols2delete = 'col1,col2,col3';
SET @sql = CONCAT(
'SELECT ',
(
SELECT GROUP_CONCAT( IF(FIND_IN_SET(COLUMN_NAME, @cols2delete), NULL, COLUMN_NAME ) )
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tablename AND TABLE_SCHEMA = @database
),
' FROM ',
@tablename);
SELECT @sql;
如果确实有很多cols,则使用此sql语句更改group_concat_max_len
SET @@group_concat_max_len = 2048;
我喜欢@Mahomedalid的回答,除了@Bill Karwin评论中提到的事实。@Jan Koritak提出的可能的问题是真的,我遇到过,但我找到了一个技巧,只是想在这里与面临这个问题的人分享。
我们可以在Prepared语句的子查询中用where子句替换replace函数,如下所示:
使用我的表和列名
SET @SQL = CONCAT('SELECT ', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users' AND COLUMN_NAME NOT IN ('id')), ' FROM users');
PREPARE stmt1 FROM @SQL;
EXECUTE stmt1;
因此,这将只排除字段id,而不包括company_id