views:

21

answers:

3

These are my 2 tables:

CREATE TABLE `documents` (
  `Document_ID` int(10) NOT NULL auto_increment,
  `Document_FolderID` int(10) NOT NULL,
  `Document_Name` varchar(150) NOT NULL,
  PRIMARY KEY  (`Document_ID`),
  KEY `Document_FolderID` (`Document_FolderID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=331 ;


CREATE TABLE `files` (
  `File_ID` int(10) NOT NULL auto_increment,
  `File_DocumentID` int(10) NOT NULL,
  `File_Name` varchar(255) NOT NULL,
  PRIMARY KEY  (`File_ID`),
  KEY `File_DocumentID` (`File_DocumentID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=333 ;

There can be multiple files to 1 document. I am trying to SELECT all of the documents with a JOIN on the files table but I only want 1 file record which is the latest one.

Here is my query I have come up with that doesn't quite work, can anyone suggest the right way?

SELECT `documents`.*
    FROM `documents`
      INNER JOIN (
        SELECT MAX(`File_ID`), *
        FROM `files`
        WHERE `File_DocumentID` = `documents`.`Document_ID`
        GROUP BY `File_ID` ) AS `file1`
      ON `documents`.`Document_ID` = `file1`.`File_DocumentID`
    WHERE `documents`.`Document_FolderID` = 94
    ORDER BY `documents`.`Document_Name`

*edit: the error is Unknown column 'documents.Document_ID' in 'where clause'

A: 

Don't group by file_id, but by File_documentid.

onof
A: 

I think I see what's wrong... You have GROUP BY File_ID, but I guess you really want GROUP BY File_DocumentID instead.

Amadan
Thanks but I am still getting Unknown column 'documents.Document_ID' in 'where clause'
fire
@fire: That's because you're attempting to use it as a correlated subquery in a derived table/inline view - won't work.
OMG Ponies
+2  A: 

Use:

SELECT d.*, f.*
  FROM DOCUMENTS d
  JOIN FILES f ON f.file_document_id = d.document_id
  JOIN (SELECT t.file_document_id,
               MAX(t.file_id) AS max_file_id
          FROM FILES t
      GROUP BY t.file_document_id) x ON x.file_document_id = f.file_document_id
                                    AND x.max_file_id = f.file_id

The derived table/inline view called "x" is a join to the same table, all it does is tweak the records coming from the FILES table to be the highest per file_document_id...

OMG Ponies
awesome thanks!
fire
there you go, with icing and sugar!
fire
@fire: Thank you :)
OMG Ponies