MySQL - JOIN or WHERE to link tables correctly?
Archive - Originally posted on "The Horse's Mouth" - 2005-12-01 06:46:00 - Graham EllisMySQL tables can be joined using two different syntaxes - one that simply lists the tables to be joined and then uses a where clause to select how the join is done, and the second using an explicit join keyword. Here's an example of both syntaxes in use, linking a table of estate agents (realtors) to the houses they have currently got for sale:
select agent, town, phone, aid, agid, sid, locate, asking from agents join sales on aid = agid;
select agent, town, phone, aid, agid, sid, locate, asking from agents, sales where aid = agid;
The results produced are identical and in the case of MySQL I understand that they both run with equal efficiency - the "where" format one being recognised by the MySQL daemon as a join and converting it across.
However, I strongly recommend that you use the join syntax.. Here's why ...
There are two types of element in a database selection command - there are MANDATORY or RULE elements which effect the validity of the data returned and if you get them wrong, the data back is going to be just plain rubbish. For example, if you were to join a table of estate agents to houses based on the street number of the house, you might well get a result set out but it would be a complete fantasy, with agent number 12 linked to all people who happen to be selling a house at number 12 in the street. So joining tables MUST be correctly applied and is a RULE element.
By contrast, choosing the data columns you want, the order of sorting, and whether or not you want properties over 200000 pounds to be returned is an OPTIONAL or REQUEST element - although you may not get back want to want if you give your MySQL the wrong request, what you'll get back will be the answer to a question that may be validly asked.
By using a join clause, you're labelling the connection of the tables as being a RULE whereas any where clauses you apply are REQUESTs. This makes automated coding much cleaner, and automation much easier.
If you want to try out this example on your own MySQL server, you can view and save the data and MySQL commands from here