Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dumping data from views in mysql

i have a view and want to extract its data into a file that has create table statement as well data. i know that mysqldump doesn't work on views.

like image 312
hd. Avatar asked Nov 24 '10 08:11

hd.


People also ask

How do I dump a view in MySQL?

Following is the syntax of the mysqldump utility. The parameters are as following: -u [user_name]: It is a username to connect to the MySQL server. To generate the backup using mysqldump, 'Select' to dump the tables, 'Show View' for views, 'Trigger' for the triggers.

What is dumping data in MySQL?

The mysqldump client utility performs logical backups, producing a set of SQL statements that can be executed to reproduce the original database object definitions and table data. It dumps one or more MySQL databases for backup or transfer to another SQL server.

How do I dump an entire database in MySQL?

To dump/export a MySQL database, execute the following command in the Windows command prompt: mysqldump -u username -p dbname > filename. sql . After entering that command you will be prompted for your password.


1 Answers

Obviously, there isn't an automated way to generate the CREATE TABLE statement of a table that does not exist. So you basically have two options:

  1. Create an actual table, dump it and remove it afterwards.
  2. Write a lot of code to analyse the view and underlying tables and generate the appropriate SQL.

First option is not optimal at all but it's easy to implement:

CREATE TABLE my_table AS
SELECT *
FROM my_view

You can now dump the table with mysqldump. When you're done:

DROP TABLE my_table

Second option can be as optimal as you need but it can get pretty complicate and it depends a lot on your actual needs and tool availability. However, if performance is an issue you can combine both approaches in a quick and dirty trick:

CREATE TABLE my_table AS
SELECT *
FROM my_view
LIMIT 1;

SHOW CREATE TABLE my_table;

Now, you use your favourite language to read values from my_view and build the appropriate INSERT INTO code. Finally:

DROP TABLE my_table;

In any case, feel free to explain why you need to obtain SQL code from views and we may be able to find better solutions.

like image 156
Álvaro González Avatar answered Sep 18 '22 05:09

Álvaro González