I need to export the data and structure of a table but the data must have a specific condition (WHERE status=0 and id>20).
How to export mysql database based on a where condition from phpMyAdmin or anything.
Using SQL from the mysql command-line:
SELECT * from YOURTABLE
WHERE status=0 and id>20
INTO OUTFILE 'yourtable.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
or using mysqldump with the --where= option:
mysqldump -u youruser -p yourdbname yourtablename --where="status=0 and id>20">yourtable.sql
Using phpMyAdmin you can execute the query in the GUI & click "export" under the resultset.
In my case from table_name ....
before INTO OUTFILE
gives an error(Unexpected ordering of clauses. (near "FROM" at position 10)
).
What works for me.
SELECT *
INTO OUTFILE '/Volumes/Development/sql/sql/enabled_contacts.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM table_name
WHERE column_name = 'value'
mysqldump --no-create-db --no-create-info --complete-insert \
-u<yourUsername> -p<yourPassword> -h<yourDbHost> -P<yourDbPort> \
<yourDatabaseName> <yourTableName> --where="status=0 and id>20"
Please be aware of that by default mysqldump will try to lock the table first, so in case you meet an error about lacking of privilege for locking table, probably you need --single-transaction
also, see https://stackoverflow.com/questions/104612/run-mysqldump-without-locking-tables for not locking table for different db engines.
For example in MySQL Workbench, you can run the select and export the query result to a csv file.