I am having trouble getting this complicated select to work for me.
Here is a graphic of my structure.
http://www.bandwise.com/files/tester_db.png
SQL file of the structure and sampe data.
http://www.bandwise.com/files/tester_db.sql
To put is simply, I have a table called “leases” and one called “apartments.” There is a one to many relationship between leases and apartments. Apartments identify a U.S. state and county in which they belong. Therefore, a given lease may have many apartments scattered across the country.
What I need to do is select ONLY U.S. states which contain one or more apartments and return a count of how many leases apply. Because some leases may have apartments in multiple states, a lease may need to be counted in multiple states.
Here is a test query that I’m working with.
SET @timenow = 1360855314;
SELECT l.lid, c.aid, c.leaseid, c.serialnum, c.state, c.county
FROM leases l, apartments c
WHERE c.leaseid = l.lid
AND l.closebidding > @timenow AND l.status = 1;
I can see here that I have 6 leases in state #1 (Texas) and 2 leases in state #2 (Louisiana). How do I go about querying from the states table outward to get the number of leases based on where their apartments are located?
The return should look like this.
---------------------------
| state | total |
---------------------------
| Texas | 6 |
---------------------------
| Louisiana | 3 |
---------------------------
Use a
count(distinct l.lid):SQL Fiddle