Archive for the ‘MySQL’ Category

Fetching specific rows from a group with MySQL

Friday, March 12th, 2010

In a normalized database, we store separate entities in separate tables and define relationships between them, those being - one-to-one, one-to-many and many-to-many. We often want to fetch data which is split over two or more related tables, which is dead simple when fetching the extra data from the 'one' side of a relationship (ie, from a "parent" table):

SELECT product_images.src,products.name
FROM product_images
INNER JOIN products ON product_images.parent_id=products.id

Literally: Get the name of the parent product for each row in the products_images table.

Going the other direction is not as trivial. If we just want all the referenced rows in the child table, the query seen before would do the trick. But if we wanted a specific row to be found - for example, the latest inserted image, it becomes somewhat more complicated.
(more...)

Multiple row operations in MySQL / PHP

Thursday, May 14th, 2009

Multiple row operations are in common use in a normalized application databases as one database entity is often linked to multiple sub-entities (for example a user and his tags). By row operations I'm referring to write queries, namely UPDATE and INSERT queries (DELETE is less interesting so I'll leave it out for now).

Too often I've seen such queries ran in long loops one at a time, which is very bad for performance (as I will show here) and sometimes equally bad for integrity (if the process is interrupted). So what are the alternatives?
(more...)

Selecting closest values in MySQL

Monday, February 2nd, 2009

Sometimes the need arises to select several values in the vicinity of a certain value, preferably ordered by proximity. The values might be dates, zip-codes or any other meaningfully ordered values that can be represented as numerical values. How can we pull this off in MySQL?
(more...)

Optimizing OR (union) operations in MySQL

Wednesday, October 15th, 2008

In my last post on database optimization, I focused on improving query performance by optimizing schema - exploring indexing strategies by reading the execution plan. In this post I'll show how different query structures can also have a major impact on performance.
(more...)

Profiling queries with Zend_Db and optimizing them by hand

Sunday, October 12th, 2008

Database performance is one of the major bottlenecks for most web applications. Most web developers are not database experts (and I'm no exception), there are however several basic methods to analyze and optimize database performance without resorting to expert consultants (such as those, whose founders blogs are an invaluable source of MySQL knowledge).
(more...)