Spiga

Copying a MySQL row to another table

My suggestion is to do the following three steps when you need to change
an account name:

1. Use UPDATE to change the account name in settings_a, even if though
changes the first letter so the account doesn't belong in that table
anymore.

UPDATE settings_a SET account = 'bishop' WHERE account = 'ash';

2. Copy the record to the correct table, according to the first letter.
Use INSERT without specifying the columns, and SELECT * without
specifying the columns. If the number, type, and order of the columns
in both tables match, it _should_ work.

INSERT INTO settings_b
SELECT * FROM settings_a WHERE account = 'bishop';

3. Remove the old record from the old table.

DELETE FROM settings_a WHERE account = 'bishop';

Export from MySQL to CSV

Using command line tools to export data from a MySQL database into a CSV file is quite easy. Here's how:
mysql -uexampleuser -pletmein exampledb -B -e "select * from \`person\`;" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > filename.csv
Here is some sample output of the above:
"id","username","group","password"
"1","tux","admin","5f4dcc3b5aa765d61d8327deb882cf99"
"2","tlugian","admin","5f4dcc3b5aa765d61d8327deb882cf99"
"3","saiyuki","admin","5f4dcc3b5aa765d61d8327deb882cf99"
"4","fred","staff","5f4dcc3b5aa765d61d8327deb882cf99"
"5","barney","staff","5f4dcc3b5aa765d61d8327deb882cf99"
"6","wilma","admin","5f4dcc3b5aa765d61d8327deb882cf99"
And now for the explanation:
Starting with the MySQL command. I wont explain the -u and -p options they are straight forward (if in doubt man mysql). The -B option will delimit the data using tabs and each row will appear on a new line. The -e option denotes the command to run once you have logged into the database. In this case we are using a simple SELECT statement.
Onto sed. The command used here contains three seperate sed scripts:
s/\t/","/g;s/^/"/        <--- this will search and replace all occurences of 'tabs' and replace them with a ",".
;s/$/"/;    <--- This will place a " at the start of the line.
s/\n//g    <---- This will place a " at the end of the line.
After running the result set through sed we redirect the output to a file with a .csv extension.
Regards, Bawdo2001

ShareThis