views:

207

answers:

1

I was wondering if there is a way to simplify this down from two queries to a single one. I'd like to be able to sort the data as I pull it out of the database and this would allow me to do it.

The tables are setup like:

table: files
------------------------
fileID (INT) | domainID (INT)
------------------------

table: domains
------------------------
domainID (INT) | domainName (text)
------------------------

table: serverFiles
------------------------
fileID (INT) | uniqueUploads (INT)
------------------------

I am currently running this query first:

SELECT domains.domainName, files.fileID, COUNT(files.fileID) 
FROM domains, files 
WHERE files.domainID = domains.domainID 
GROUP BY files.domainID;

Then looping through the results of that query I am running a second query using the fileID resulting from the first query ($fileIDFromFirstQuery):

SELECT serverFiles.uniqueUploads 
FROM serverFiles 
WHERE serverFiles.fileID = '$fileIDFromFirstQuery';

The results come out like:

Domains     |   Files with Domain | Unique Uploads 
--------------------------------------------------
domain1.com         32            1412
domain2.com         21             699
domain3.com             52                  293

Thanks for any assistance.

+1  A: 

I think this should work:

SELECT domains.domainID, domainName, COUNT(*), SUM(uniqueUploads)
FROM domains
INNER JOIN files ON files.domainID = domains.domainID
INNER JOIN serverFiles on serverFiles.fileID = files.fileID
GROUP BY domains.domainID, domainName

ETA:

Maybe I'm not seeing everything here, but why not just get rid of the serverFiles table and put "uniqueUploads" on the files table? Unless maybe you are sharing files between multiple domains, in which case it would make sense.

Eric Petroelje