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

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


当前回答

也许我有一个解决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'

其他回答

即使要查询所有列,也最好指定要查询的列。

因此,我建议您在语句中写下每一列的名称(不包括您不想要的列)。

SELECT
    col1
    , col2
    , col3
    , col..
    , col53

FROM table

如果你使用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;

现在你可以删除那些你不想要的。

如果愿意,可以使用SQL生成SQL,并对生成的SQL进行评估。这是一种通用的解决方案,因为它从信息模式中提取列名。下面是一个Unix命令行的示例。

替换

MYSQL的MYSQL命令 带有表名的TABLE 包含排除字段名的EXCLUDEDFIELD

echo $(echo 'select concat("select ", group_concat(column_name) , " from TABLE") from information_schema.columns where table_name="TABLE" and column_name != "EXCLUDEDFIELD" group by "t"' | MYSQL | tail -n 1) | MYSQL

实际上,您只需要以这种方式提取列名一次,就可以构造排除该列的列列表,然后只需使用已构造的查询。

比如:

column_list=$(echo 'select group_concat(column_name) from information_schema.columns where table_name="TABLE" and column_name != "EXCLUDEDFIELD" group by "t"' | MYSQL | tail -n 1)

现在可以在构造的查询中重用$column_list字符串。

这个问题是关于MySQL的,但我仍然认为值得一提的是,至少谷歌BigQuery和H2原生支持* EXCEPT语法。

SELECT * FROM actor

生产:

|actor_id|first_name|last_name   |last_update            |
|--------|----------|------------|-----------------------|
|1       |PENELOPE  |GUINESS     |2006-02-15 04:34:33.000|
|2       |NICK      |WAHLBERG    |2006-02-15 04:34:33.000|
|3       |ED        |CHASE       |2006-02-15 04:34:33.000|

SELECT * EXCEPT (last_update) FROM actor

生产:

|actor_id|first_name|last_name   |
|--------|----------|------------|
|1       |PENELOPE  |GUINESS     |
|2       |NICK      |WAHLBERG    |
|3       |ED        |CHASE       |

也许,MySQL的未来版本也会支持这种语法?

我喜欢@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