I think it is easier if I explain what I am trying to do.
Say I have 2 tables, one is pages and the other is views.
Each page has a unique ID, when the page is visited, a record is entered in to the views.
Say I wanted to list the pages and the total views of the page together.
So I would have a query which selects the pages from the database and uses a loop to display them, but I want to also find out the total views it has and display that number next to the page name.
How would I achieve this?
When I run a query inside a fetch loop, I get the following error:
Commands out of sync; you can't run this command now
Thanks.
Use a join, something like this:
By using
LEFT OUTER JOIN, pages without views will still be returned, but the columns fromviewwill beNULL.This will get you all of the results you need in one single query. It’s usually better to have the database engine do the work of correlating tables together than to do so on your own. Then you’re only making one trip to the database engine, and it can perform the correlation much faster than your code can.
To get the count, you can either do a join-with-group-by (which may be an ugly query, depending on your DB engine) or a query with a subquery:
The group-by variant would look something like this:
Depending on your DB engine and schema, you may have to group by more than
page.id.A decent query planner will turn the subquery example into a join, so the performance of the two queries should be similar, if not identical. Nevertheless, you should use
EXPLAINto determine if one variant gets optimized better than the other.