Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql create view from working "prepare" statement

Tags:

sql

mysql

I have an SQL query

SELECT CONCAT(
  'SELECT `table`.id', GROUP_CONCAT(CONCAT('
     ,    `t_', REPLACE(name, '`', '``'), '`.value
         AS `', REPLACE(name, '`', '``'), '`'
   ) SEPARATOR ''),
 ' FROM `table` ', GROUP_CONCAT(CONCAT('
     LEFT JOIN `table`   AS `t_', REPLACE(name, '`', '``'), '`
            ON `table`.id = `t_', REPLACE(name, '`', '``'), '`.id
           AND `t_', REPLACE(name, '`', '``'), '`.name = ', QUOTE(name)
   ) SEPARATOR ''),
 ' GROUP BY `table`.id'
) INTO @qry FROM (SELECT DISTINCT name FROM `table`) t;

PREPARE stmt FROM @qry;
EXECUTE stmt;

from this question here. Honestly, I barely understand it, I'm surprised it is even possible, but after modifying some names it does exactly what I need, but I need it in a "View".

How would I add this to a view in my database?

Many Thanks

like image 274
James Taylor Avatar asked Oct 20 '25 13:10

James Taylor


1 Answers

I guess it's a while this question was asked, but I know this is possible.

A little modification to the last section of your prepared query as shown below will help you achieve your aim:

Just modify before the PREPARE stmt

SET @qrys = CONCAT('CREATE OR REPLACE VIEW "put_your_view_name_without_quote" AS ',@qry);
PREPARE stmt FROM @qrys;
EXECUTE stmt;
like image 65
Abiodun Emman Avatar answered Oct 22 '25 03:10

Abiodun Emman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!