Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific columns, along with the rest

Tags:

mysql

I have a table with a lot of columns. Some of these are DATETIME, which I turn into Unix timestamps with UNIX_TIMESTAMP(). So I don't have to type out all the other columns I want from the table, is there a way of doing something like:

SELECT UNIX_TIMESTAMP(t.start) AS start,
       UNIX_TIMESTAMP(t.end) AS end,
       t.theOtherColumns
FROM table t

Where t.theOtherColumns is the rest of the columns in the table. To explain further; I want to select all the columns from the table, perform operations on some of them, but not type out each column name into the query.

When I do, say,

SELECT UNIX_TIMESTAMP(t.start) AS start,
       UNIX_TIMESTAMP(t.end) AS end,
       t.theOtherColumns
FROM table t

It selects start and end twice. I only want to return the start and end columns from UNIX_TIMESTAMP(), and exclude those columns from the t.* set.

like image 524
Bojangles Avatar asked Sep 15 '11 13:09

Bojangles


3 Answers

What you can do is use this answer to help build the results you want.

A possible solution would look like

SET @sql = CONCAT('SELECT UNIX_TIMESTAMP(t.start) AS start, UNIX_TIMESTAMP(t.end) as end,', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM 
information_schema.columns WHERE table_schema = 'test' AND table_name = 
't' AND column_name NOT IN ('start', 'end')), 
' from test.t');  
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

*Replace test with the name of the schema that contains your table t.

like image 109
donL Avatar answered Sep 21 '22 06:09

donL


Try t.* it works under Oracle.

like image 45
HamoriZ Avatar answered Sep 21 '22 06:09

HamoriZ


I don't believe there is a way to do this as you suggested, but you can do this

SELECT t.*, UNIX_TIMESTAMP(t.start) AS start, UNIX_TIMESTAMP(t.end) as end ...
like image 41
Brian Glaz Avatar answered Sep 19 '22 06:09

Brian Glaz