I'm trying to keep efficiency as a major focus in my applications. So here's a simple question.
In general, is it better to do two simple selects or one join?
If I have tables like this:
Table1
id1
name1
Table2
id2
id1
name2
Where Table2.id1 is a foreign key for Table1.id1.
Let's say that I have a shopping cart or similar system. I want to display name1 on the top of the page and then show a list of all items that are joined to it.
I could do two simple queries, "SELECT name1 FROM Table1 WHERE id1=$id1" and then "SELECT name2 FROM Table2 WHERE id1=$id1".
Or I could join them like this, "SELECT name1,name2 FROM Table1,Table2 WHERE Table1.id1=Table2.id1 AND Table1.id1 = $id1".
With this simple result set, both would be pretty fast. However real world cases are always much more complex than this.
So if I'm designing an application and I want my response and load on the webserver and database server to be as fast as possible, which should I use (when all else is equal)?
I've thought it through in my head and had two conclusions.
First, Doing a query certainly has some overhead. PHP and/or the database have to keep track of a recordset for each query.
Secondly, Doing a join has some overhead as well. Additionally, every record in the joined recordset contains two fields. One of these fields is only needed one time at the onset.
I've heard that there are tools that will annalyze your query and help you understand the "costs" associated with it. I've never used one before but I'd like to. If there's a tutorial out there or an easy to understand tool, pointers would be appreciated. FYI, I typically use PostgreSQL or MySQL for my applications (Postgres being used more often).