Joining two tables and counting one
Hello,
I have a problem with MySQL and php
I am new to SQL statements
I have two tables
Table1: Customers
Fields: Name, Address, City, Region
Table 2: Regions
Fields: ID, Region name
For filter purposes I want to fill a dropdownlist with all Regions that do have some customers. But this should also show the number of Customers in the Region so a list like:
Region 1 (13)
Region 2 (5)
Region 3 (28)
I like the Regions to be sorted Alphabeticly by Name.
First I did
SELECT * FROM Regions
For every region I counted the Customers with a
SELECT * FROM Customers WHERE Region=$RegionID
Since I was filling 6 similar dropdownlists this way the page loaded slow (2,5 to 3 seconds query time)
I managed to speed up the code a lot with this statement on the Customer table
SELECT Region, COUNT(*) AS numrows FROM Customers GROUP BY Region
Now the six lists are filled in 0.05 seconds quite an improvement. But now my lists fo know the Region ID and how many customers there are. But no region name.
Now I am able to get the name by doing a SELECT Region name FROM Regions WHERE ID=$Region that I got from the Customer table.
But this gives me two problems:
First: The list of regions is not sorted by Region name but in the order the regions were found in the customer table.
Problem 2: The query time increased to 0.2 seconds again.
I do have a feeling that when I am able to combine the two tables with some sort of JOIN command I can increase the speed. I sure like to, since the real data in the database will only become more and more compared to the amount of records I'm now testing with.
Can anyone help me to make a statement that achieves at least the sorting and if possible also to get a better performance?
Subject
Written By
Posted
Joining two tables and counting one
June 02, 2005 01:13PM
Sorry, you can't reply to this topic. It has been closed.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion
of Oracle or any other party.