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'