Archive for category mysql

Selecting a random row using MySQL

There are many examples where you would need to retrieve a random record or more from a set of tables. For example your page template may be cycling through QOTDs, testimonials, offers, specials, and so forth.

To retrieve a random row in MySQL, use the ORDER BY RAND() statement to randomly order the rows of a table. Then use LIMIT x to retrieve the first x rows from the randomised representation of the table.

For example:

SQL:
  1. /*  Retrieve 5 random special offers to display in your e-commerce store's sidebar */
  2. SELECT  offer_id
  3. FROM    special_offers
  4. ORDER BY RAND()
  5. LIMIT 5

Of course, we can make our query as complex as needed, and then randomly order the resultset.

SQL:
  1. SELECT  so.offer_id, i.title
  2. FROM    special_offers so
  3.           LEFT JOIN items i ON (so.item_id = i.item_id)
  4.           LEFT JOIN item_categories ic ON (i.item_id = ic.item_id)
  5. WHERE   ic.category_id = 2344
  6. ORDER BY RAND()
  7. LIMIT 5

No Comments

Using mysqldump to export a database

mysqldump is a useful utility for dumping the contents of an entire database to an SQL file.

CODE:
  1. mysqldump --user=dbusername --password=dbpassword db_name_here> db_name_here.sql

By default the --opt option is enabled, which is a shorthand option for specifying the below options. According to the documentation, using this option "... should give you a fast dump operation and produce a dump file that can be reloaded into a MySQL server quickly".

CODE:
  1. --add-drop-table
  2. --add-locks
  3. --create-options
  4. --disable-keys
  5. --extended-insert
  6. --lock-tables
  7. --quick
  8. --set-charset

No Comments