Select all columns except one in MySQL?

2018-12-31 04:29发布

I'm trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this?

EDIT: There are 53 columns in this table (NOT MY DESIGN)

标签: mysql select
28条回答
荒废的爱情
2楼-- · 2018-12-31 05:05

You can do:

SELECT column1, column2, column4 FROM table WHERE whatever

without getting column3, though perhaps you were looking for a more general solution?

查看更多
路过你的时光
3楼-- · 2018-12-31 05:08

Based on @Mahomedalid answer, I have done some improvements to support "select all columns except some in 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;

If you do have a lots of cols, use this sql to change group_concat_max_len

SET @@group_concat_max_len = 2048;
查看更多
低头抚发
4楼-- · 2018-12-31 05:08

Agree on @Mahomedalid's answer. But I didn't wanted to do something like prepared statement and I didn't wanted to type all the fields. So What I had was a silly solution. Go to the table in phpmyadmin->sql->select, it dumps the query copy replace and done! :)

查看更多
宁负流年不负卿
5楼-- · 2018-12-31 05:11

Just do

SELECT * FROM table WHERE whatever

Then drop the column in you favourite programming language: php

while (($data = mysql_fetch_array($result, MYSQL_ASSOC)) !== FALSE) {
   unset($data["id"]);
   foreach ($data as $k => $v) { 
      echo"$v,";
   }      
}
查看更多
看淡一切
6楼-- · 2018-12-31 05:12

I liked the answer from @Mahomedalid besides this fact informed in comment from @Bill Karwin. The possible problem raised by @Jan Koritak is true I faced that but I have found a trick for that and just want to share it here for anyone facing the issue.

we can replace the REPLACE function with where clause in the sub-query of Prepared statement like this:

Using my table and column name

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;

So, this is going to exclude only the field id but not company_id

Hope this will help anyone looking for a solution.

Regards

查看更多
旧时光的记忆
7楼-- · 2018-12-31 05:12

While I agree with Thomas' answer (+1 ;)), I'd like to add the caveat that I'll assume the column that you don't want contains hardly any data. If it contains enormous amounts of text, xml or binary blobs, then take the time to select each column individually. Your performance will suffer otherwise. Cheers!

查看更多
登录 后发表回答