Everybody familiar with MySQL database knows mysqldump, the ultimate MySQL backup tool. This tool has more intereseting features, mainly it can be used to dump only specific tables or even selectively extract data from the database.
So if You want to dump a single table, you should execute:
mysqldump -u db_user -p db_name table_name > table_and_data.sql
This is a default script, quite useful for recreating tables/making backups. But as it was mentioned before, we just want the data. Fortunately mysqldump comes with many options, --no_create_info for instance will drum only the data wrapped by an INSERT INTO statement. Another nice option: --where enables providing custom data filtering rules (typical for MySQL). Let's try a query that dumps specific rows from a table that is related to another table using a WHERE statement on the corresponding data model.
mysqldump -u db_user -p db_name table_name --no_create_info \
--lock-all-tables --where 'id in (select tn.id from table_name as tn \
join related_table as rt on tn.related_table_id = rt.id \
where rt.some_field = 1)' > data.sql
The idea is to use a subselect to get table_name rows that have foreign keys to the related_table rows that meet the rt.some_field = 1 requirement. This works well, however if You access tables not specified in mysqldump's command params, You should lock them yourself. In this example I use --lock-all-tables which is an overkill (if You're using a transactional database engine, such as InnoDB, You can use --single-transaction instead - no table locking will be required).
Cheers!
~KR
Thanks man, just helped me a lot.
ReplyDeleteI have one doubt..
ReplyDeleteI am trying to do same thing..but instead of multiline command,i keppt my select query in one variable but when translation,it is giving stange errors.
BDW THANKS MAN FOR THIS MULTILINE WAY.
I have one doubt..
ReplyDeleteI am trying to do same thing..but instead of multiline command,i keppt my select query in one variable but when translation,it is giving stange errors.
BDW THANKS MAN FOR THIS MULTILINE WAY.
Thanks man, just helped me a lot.
ReplyDeletekuşadası
ReplyDeletemilas
çeşme
bağcılar
siirt
GFY