Selecting all fields except only one field in mysql

65,830

Solution 1

you can do it easily like that

lets say your field is an id = 5

then

   select * from your_table where id !=5 

and if you mean columns

lets say you dont want select column3

then

   select column1,column2,column4 from tablename;

if you have many columns

    SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME),  '<columns_to_delete>,', '') 
    FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>'   AND TABLE_SCHEMA = '<database>'), ' FROM <table>');

    PREPARE stmt1 FROM @sql;
   EXECUTE stmt1;

Solution 2

Yes you can fetch from information_schema.columns

SET @sql = CONCAT('SELECT ', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM 
information_schema.columns WHERE table_schema = 'dbo' AND table_name = 
'tablename' AND column_name NOT IN ('c1', 'c2')), 
' from dbo.tablename');  

PREPARE stmt1 FROM @sql;

EXECUTE stmt1;

Solution 3

Try this -

SHOW FIELDS FROM `tablename` WHERE FIELD NOT IN ('f1','f2','f3');

Execute this query and fetch the specific field-names and put each field-name into an array. then implode the array with ',' inside the select query.

$fields = implode(',',$fields_arr);
$sql = SELECT $fields FROM `tablename`;
Share:
65,830
Deepu
Author by

Deepu

Full stack web developer with experience in php,javascript,jquery,html,mysql,Zend, Laravel, Codeigniter, Agile, Nodejs etc.. profile for 웃웃웃웃웃 on Stack Exchange, a network of free, community-driven Q&amp;A sites http://stackexchange.com/users/flair/1570947.png

Updated on November 03, 2020

Comments

  • Deepu
    Deepu over 3 years

    Possible duplicate:
    Select all columns except one in MySQL?

    I want to know is there a way to select all fields except one field from a table in my database.

    I know I can describe the field names in the select query.
    For example:

    SELECT fieldname1, fieldname2, fieldname3, fieldname4 FROM tablename;
    

    But my question is, is there any way to do it in a simple way... Like this

    SELECT * FROM tablename EXCEPT(fieldname3);
    

    I am using MySQL and Zend framework.

  • SSH This
    SSH This over 10 years
    Wow no wonder people are scarpering from sql, what a mess
  • Juan Vilar
    Juan Vilar about 9 years
    nope, this does not work ,not at least in MYSQL it doesnt
  • Juan Vilar
    Juan Vilar about 9 years
    The Proper way for this approach would be IN MYSQL SHOW COLUMNS FROM <TABLENAME> WHERE Field !='<COLUMNNAME>'
  • alexandre-rousseau
    alexandre-rousseau over 6 years
    SHOW FILEDS & SHOW COLUMNS give me the same result on MySQL 5.7.19-0ubuntu0.16.04.1