I am creating view which selects various number of columns from the various tables accumulating numerous columns in the view say
col1, col2,..............,coln
When i need sum of all these columns I need to write as
SELECT col1+col2+............+coln FROM myview
I want trick that I can get the sum without have to mentioning all the column name.
You need dynamic SQL to do this:
http://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
An example:
SELECT concat( 'SELECT ', group_concat( COLUMN_NAME SEPARATOR '+' ),
' FROM ', 'myview' )
FROM information_schema.columns
WHERE TABLE_NAME= 'myview'
INTO @s;
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
A working demo on SQLFiddle: http://sqlfiddle.com/#!9/4835b/1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.