如何“选择*"从MySQL中的表中删除某些列? [英] How can I "select *" from a table in MySQL but omit certain columns?

查看:242
本文介绍了如何“选择*"从MySQL中的表中删除某些列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下列的表格:

I have a table with the following columns:

id,name,age,surname,lastname,catgory,active

而不是:SELECT name,age,surname,lastname,catgory FROM table

我该如何做这样的事情:SELECT * FROM table [but not select id,active]

How can I make something like this: SELECT * FROM table [but not select id,active]

推荐答案

许多人说,最好的方法是显式列出要返回的每一列,但在某些情况下,您可能希望节省时间并从结果中省略某些列(例如测试).下面,我给出了解决此问题的两个选项.

While many say it is best practice to explicitly list every column you want returned, there are situations where you might want to save time and omit certain columns from the results (e.g. testing). Below I have given two options that solve this problem.

1.创建一个函数,该函数可检索所有所需的列名:(我创建了一个称为函数的架构来保存此函数)

1. Create a Function that retrieves all of the desired column names: ( I created a schema called functions to hold this function)

DELIMITER $$

CREATE DEFINER=`root`@`%` FUNCTION `getTableColumns`(_schemaName varchar(100), _tableName varchar(100), _omitColumns varchar(200)) RETURNS varchar(5000) CHARSET latin1
BEGIN
    SELECT GROUP_CONCAT(COLUMN_NAME) FROM information_schema.columns 
    WHERE table_schema = _schemaName AND table_name = _tableName AND FIND_IN_SET(COLUMN_NAME,_omitColumns) = 0 ORDER BY ORDINAL_POSITION;
END

创建并执行select语句:

Create and execute select statement:

SET @sql = concat('SELECT ', (SELECT 
functions.getTableColumns('test', 'employees', 'age,dateOfHire')), ' FROM test.employees'); 
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

2.或者不编写函数就可以:

SET @sql = CONCAT('SELECT ', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM 
information_schema.columns WHERE table_schema = 'test' AND table_name = 
'employees' AND column_name NOT IN ('age', 'dateOfHire')), 
' from test.eployees');  
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

*用您自己的模式名称替换测试

*Replace test with your own schema name

**用您自己的表名替换员工

**Replace employees with your own table name

***用您要忽略的列替换年龄,dateOfHire(您可以将其保留为空白以返回所有列,或仅输入一个要忽略的列名)

***Replace age,dateOfHire with the columns you want to omit (you can leave it blank to return all columns or just enter one column name to omit)

** **您可以根据需要调整函数中varchar的长度

** **You can adjust the lengths of the varchars in the function to meet your needs

这篇关于如何“选择*"从MySQL中的表中删除某些列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆