简体   繁体   中英

Dump mysql by mysql query

Is there some way to export mysql table by query. Something like this, but mysql format, not csv:

SELECT * from myTable INTO OUTFILE '/tmp/querydump.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'

So I want receive file in this format:

INSERT INTO `Cheks` (`Sum`,`Nal`,`Discount`,`Oldkas`,`User`,`Kasm`,`Kas`,`Dat`,`Isreturn`,`Fil`,`Round`,`Chds`) VALUES (12.00,500.00,0.00,188.120,8,1,'N1','2019/10/04 06:28:10',0,0,0,0.00);

I know about mysqldump, but the point is to receive dump by mysql query. It may be query result, not file, does not metter.

On (dirty) thing that you could do is write a query that returns a single column dataset where earch record contains the INSERT command. This can be done using string concatenation.

Consider:

SELECT CONCAT(
    'INSERT INTO `Cheks` (`Sum`,`Nal`,`Discount`,`Oldkas`,`User`,`Kasm`,`Kas`,`Dat`,`Isreturn`,`Fil`,`Round`,`Chds`) VALUES(' 
    `Sum`, ', ', 
    `Nal`, ', ', 
    `Discount`, ', ', 
    `Oldkas`, ', ', 
    `User`, ', ', 
    `Kasm`, ',' , 
    '''', `Kas`, ''', ',
    '''', `Dat`, ''', ',
    `Isreturn`, ', ',
    `Fil`, ', ',
    `Round`, ', '
    `Chds`,
    ');' 
from myTable 
INTO OUTFILE '/tmp/querydump.csv' 

The thing to be careful again is quoting: numeric columns should not be quoted, while others should. The above code takes care of that. You also have to worry about the possibility that a text column might contain embedded single quotes (for date columns, there is no such risk). So in your use case if Kas might contain embedded quotes, then you would need to escape them by doubling them, using REPLACE() .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM