This engine allows you to define a table that sucks data from another table, even from a remore server. The tables definition must be the same.
I use it for the following:
Every time I rebuild the project, I have wait for 15 minutes while two big tables are created and filled with data — these are geo data tables (world cities, regions, etc), 4 mln records, and POI table, 2 mln records. I use Federated tables to create two separate databases and just link these tables in my project.
These tables are shared between several environments (dev, test and live) on the same server.
To check if your MySQL server has the Federated engine supported, you can use just a phpMyAdmin — go to home page of you phpMyAdmin installation (click Home picture), then choose Engines tab and check there.
If it’s not enabled (gray), open your my.ini file, find the “[mysqld]” part and make it to look like this:
P.S. If you have an error in the table definition, phpMyAdmin shows your database as empty. To fix this, log in via mysql console and try to make a SELECT from this poorly defined table and you get the error message to work with.
Now let’s create a SQL function for handy converts. Create a udf.sql file and add this in it:
DROP FUNCTION IF EXISTS EXCHANGE;
CREATE FUNCTION EXCHANGE( amount DOUBLE, cFrom CHAR(3), cTo CHAR(3) ) RETURNS DOUBLE READS SQL DATA DETERMINISTIC
COMMENT 'converts money amount from one currency to another'
DECLARE rateFrom DOUBLE DEFAULT 0;
DECLARE rateTo DOUBLE DEFAULT 0;
SELECT `rate` INTO rateFrom FROM `currency` WHERE `code` = cFrom;
SELECT `rate` INTO rateTo FROM `currency` WHERE `code` = cTo;
IF ISNULL( rateFrom ) OR ISNULL( rateTo ) THEN
RETURN amount * rateTo / rateFrom;
and run this command in your shell:
mysql --user=USER --password=PASS DATABASE < udf.sql
This is how you can use this function — how to convert 10 US dollars to Canadian dollars:
SELECT EXCHANGE( 10, 'USD', 'CAD')
which results in $10 = 10.93 Canadian dollars.
P.S. Consider adding the currency export action call to your cron scripts.
P.P.S. A function to unzip the data file can be got at php.net
Data feeds often come in XML format, so your application must be able to deal with that format.
As I already wrote, data in CSV format (comma separated values) can be loaded to database extremely fast. So my idea was to convert XML data files to CSV and then use bulk load to database. My tests shown that this is faster in 10-100 times than one by one inserts.
Yesterday I decided to write a generalized solution for this, and it turned out that there is no need: it’s just coming — MySQL 6 will have such feature!
How it works: you create a table, name its columns exactly as XML nodes/attributes names or — and MySQL server will load it correspondently.
Example — you downloaded a POI list file (Points of Interest) called poi.xml that looks like this:
There are situations when you need to separate processing of big amount of data between several “agents”, e.g.:
you have a long list of websites which must be checked for being alive (404 error check) by your web-clawlers;
a queue of photos to be resized or videos to be converted;
articles that your editors must review;
catalogue of blog feeds that your system must import posts from;
The idea to do this is simple:
Give a small piece of big work to an agent.
Mark this piece as given to him (so that none other starts to do the same job) and remember the time stamp when the job was given or when the job becomes obsolete (this agent is dead, let’s give this job to someone else).
If work is done — go to step #1.
After some period of time (1 hour) check all the time stamps, and if some agents didn’t cope with the job, mark the jobs as free so that others could start to work on it.
The problem is between steps #1 and #2 — while you gave a job to Agent 1 and going to mark it as given to him, what if Agent 2 is given by the same job? If you have many Agents, this can happen at real. This situations is called concurrent read/write.
To overcome this a lock can be used.
In this article I wil explain, how to use locks in Zend project with MySQL database.
First of all, MySQL documentation tells that SELECT .. FOR UPDATE can be used for that purpose. First step is to select records by that statement, and second step is to mark them as locked. Requirements are to use InnoDB storage and to frame these two statements in a transaction.
Happily, Zend_Db_Table_Select has a special method forUpdate() that implements SELECT .. FOR UPDATE statement. Zend_Db can cope with transactions as well. Let’s try it!
To lock a record, we need two fields:
one to remember ID of agent that is processing this record (let’s call this column ‘locked_by‘)
one another to know the time when the lock becomes obsolete (let’s call this column ‘expires_at‘)
I wrote a class that inherits from Zend_Db_Table and helps to get records with locking them.
If the table has a composite primary key (containing more than one column), the ActiveRecord approach is used, so the save() method for every record is called, that’s simple (drawback — multiple update queries). Otherwise, if it is a deep-seated table with one ID column as a primary key, then the IDs are collected in a list and all records are updated by a single statement with IN in where clause (which is much faster).
TTL (‘Time to Live‘) — period of time when lock is allowed. In my application the default is one hour. Format of TTL can be seen in MySQL documentation.
And now how to use it.
Let’s imagine you have several editors that divide the big articles list and review them. My model class has a method fetchForUser() that returns no more than 5 articles for current user (by given user ID).
This is an Article table model, inherited from the class above. Usually such classes are located at
Note: if the editor refreses the page, the expres_at fields is refreshed by current time as well.
As for step four of our algorithm (releasing all obsolete locks) — create an action in your backend controller, call your table model releaseLocks() method in it and call that action periodically by Cron.
To boost the performance of the lock releasing, create an index on the expires_at column. (Because of this reason I rejected the ‘locked_since‘ column in favor of ‘expires_at‘)
P.S. In my database date/time columns have DATETIME type. If you use INT to store timestamps, convert it to unix time and back.
As certified MySQL developer (yes, I’m listed on mysql.com!!! 🙂 ), I would like to share some experience I’ve got during training to the certification. Today I will tell you how to speed up your queries.
Use persistent connections to the database to avoid connection overhead.
Check all tables have PRIMARY KEYs on columns with high cardinality (many rows match the key value). Well,`gender` column has low cardinality (selectivity), unique user id column has high one and is a good candidate to become a primary key.
All references between different tables should usually be done with indices (which also means they must have identical data types so that joins based on the corresponding columns will be faster). Also check that fields that you often need to search in (appear frequently in WHERE, ORDER BY or GROUP BY clauses) have indices, but don’t add too many: the worst thing you can do is to add an index on every column of a table 🙂 (I haven’t seen a table with more than 5 indices for a table, even 20-30 columns big). If you never refer to a column in comparisons, there’s no need to index it.
Using simpler permissions when you issue GRANT statements enables MySQL to reduce permission-checking overhead when clients execute statements.
Use less RAM per row by declaring columns only as large as they need to be to hold the values stored in them.
Use leftmost index prefix — in MySQL you can define index on several columns so that left part of that index can be used a separate one so that you need less indices.
When your index consists of many columns, why not to create a hash column which is short, reasonably unique, and indexed? Then your query will look like:
WHERE hash_column = MD5( CONCAT(col1, col2) )
AND col1='aaa' AND col2='bbb';
Consider running ANALYZE TABLE (or myisamchk --analyze from command line) on a table after it has been loaded with data to help MySQL better optimize queries.
Use CHAR type when possible (instead of VARCHAR, BLOB or TEXT) — when values of a column have constant length: MD5-hash (32 symbols), ICAO or IATA airport code (4 and 3 symbols), BIC bank code (3 symbols), etc. Data in CHAR columns can be found faster rather than in variable length data types columns.
Don’t split a table if you just have too many columns. In accessing a row, the biggest performance hit is the disk seek needed to find the first byte of the row.
A column must be declared as NOT NULL if it really is — thus you speed up table traversing a bit.
Don’t use PHP loop to fetch rows from database one by one just because you can 😉 — use IN instead, e.g.
WHERE `id` IN (1,7,13,42);
Use column default value, and insert only those values that differs from the default. This reduces the query parsing time.
Use INSERT DELAYED or INSERT LOW_PRIORITY (for MyISAM) to write to your change log table. Also, if it’s MyISAM, you can add DELAY_KEY_WRITE=1 option — this makes index updates faster because they are not flushed to disk until the table is closed
Think of storing users sessions data (or any other non-critical data) in MEMORY table — it’s very fast.
For your web application, images and other binary assets should normally be stored as files. That is, store only a reference to the file rather than the file itself in the database.
If you have to store big amounts of textual data, consider using BLOB column to contain compressed data (MySQL’s COMPRESS() seems to be slow, so gzipping at PHP side may help) and decompressing the contents at application server side. Anyway, it must be benchmarked.
If you often need to calculate COUNT or SUM based on information from a lot of rows (articles rating, poll votes, user registrations count, etc.), it makes sense to create a separate table and update the counter in real time, which is much faster. If you need to collect statistics from huge log tables, take advantage of using a summary table instead of scanning the entire log table every time.
Don’t use REPLACE (which is DELETE+INSERT and wastes ids): use INSERT ... ON DUPLICATE KEY UPDATE instead (i.e. it’s INSERT + UPDATE if conflict takes place). The same technique can be used when you need first make a SELECT to find out if data is already in database, and then run either INSERT or UPDATE. Why to choose yourself — rely on database side.
Divide complex queries into several simpler ones — they have more chances to be cached, so will be quicker.
Group several similar INSERTs in one long INSERT with multiple VALUES lists to insert several rows at a time: quiry will be quicker due to fact that connection + sending + parsing a query takes 5-7 times of actual data insertion (depending on row size). If that is not possible, use START TRANSACTION and COMMIT, if your database is InnoDB, otherwise use LOCK TABLES — this benefits performance because the index buffer is flushed to disk only once, after all INSERT statements have completed; in this case unlock your tables each 1000 rows or so to allow other threads access to the table.
Log slow queries on your dev/beta environment and investigate them. This way you can catch queries which execution time is high, those that don’t use indexes, and also — slow administrative statements (like OPTIMIZE TABLE and ANALYZE TABLE)
If you have lots of DELETEs in your application, or updates of dynamic format rows (if you have VARCHAR, BLOB or TEXT column, the row has dynamic format) of your MyISAM table to a longer total length (which may split the row), schedule running OPTIMIZE TABLE query every weekend by crond. Thus you make the defragmentation, which means more speed of queries. If you don’t use replication, add LOCAL keyword to make it faster.
Don’t use ORDER BY RAND() to fetch several random rows. Fetch 10-20 entries (last by time added or ID) and make array_random() on PHP side. There are also other solutions.
Consider avoiding using of HAVING clause — it’s rather slow.
In most cases, a DISTINCT clause can be considered as a special case of GROUP BY; so the optimizations applicable to GROUP BY queries can be also applied to queries with a DISTINCT clause. Also, if you use DISTINCT, try to use LIMIT (MySQL stops as soon as it finds row_count unique rows) and avoid ORDER BY (it requires a temporary table in many cases).
When I read “Building scalable web sites”, I found that it worth sometimes to de-normalise some tables (Flickr does this), i.e. duplicate some data in several tables to avoid JOINs which are expensive. You can support data integrity with foreign keys or triggers.
If you want to test a specific MySQL function or expression, use BENCHMARK function to do that.
Some of these hints are unapplicable if you use a framework because direct queries are uninvited guests in the case: focus on competent database optimization — tune indexes and server parameters.