How to select all columns except one in particular?

Asked

Viewed 2,531 times

12

There is the possibility to select all columns of a table:

SELECT * FROM wp_rw_programacao WHERE id = $id

But I need to eliminate the result of the column id. It is possible?

  • It’s not possible. Unless you create a function to do this.

3 answers

10


Unable to grab all columns except one or a few specific ones.

Generally catch everyone is already a mistake, gets worse when there are exceptions.

Almost every time someone wants to do this is to type less. This is not appropriate.

If you want to get a specific list you should put all of them. If you want them all, that is, if you want to change you want different columns to be changed in query automatically, there fits the *. It’s almost never what a person wants.

Do it the right semantic way you need it.

If you really want the total column list to come up minus one would have to treat this outside of SQL.

There is even an automated solution where you can read Mysql data on this table and generate the query from this, but should only do if it really needs the query be dynamic according to the current structure.

There’s an example of how to do it in Wictor Chaves' answer (but note that it’s easy to have security problems if you abuse it if you don’t know what you’re doing, especially if that $id from an external source). But do not do this to save typing, your code will be semantically wrong if it is not what you need and even if it does not bring problems now will bring in the future.

To make it work the whole system needs to be done thinking about it.

8

This way you can:

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

PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

Substitute <table>, <database> e <columns_to_omit>

source: https://stackoverflow.com/questions/9122/select-all-columns-except-one-in-mysql

6

You can call the fields you want by doing so, example:

SELECT campo1, campo2, campo3, campo4 
FROM wp_rw_programacao 
WHERE id = $id

The only fields that will be returned will be: campo1, campo2, campo3, campo4

More information.

There is no other way to do it. See here more information on Stackoverflowpt.

  • But I have many columns.

  • 1

    @Atlasilva I have about 60 columns and select in hand each =] It’s a pain, but not always programming is fun

  • Dog’s work to eliminate a column , just to complicate the code , I didn’t see a reason for this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.