SELECT f.fileID, f.title, f.categoryID, f.description, f.filename, f.serverfilename, f.filetype, f.filesize,f.uploaded,f.uploadedBy,u.firstName, u.lastName, fc.category, (SELECT count(commentID) FROM #variables.tableprefix#comments c where f.fileid = c.itemid and type = 'file') as commentcount FROM #variables.tableprefix#files f LEFT JOIN #variables.tableprefix#users u ON f.uploadedBy = u.userID LEFT JOIN #variables.tableprefix#categories fc on f.categoryID = fc.categoryID WHERE f.projectID = AND f.fileID = AND f.categoryID = AND f.uploadedBy = AND fc.type = 'file' ORDER BY f.title asc f.uploaded desc INSERT INTO #variables.tableprefix#files (fileID, projectID, title, categoryID, description, filename, serverfilename, filetype, filesize, uploaded, uploadedBy) VALUES(, , , , , , , , , , ) UPDATE #variables.tableprefix#files SET title = , categoryid = , description = WHERE projectID = AND fileID = DELETE FROM #variables.tableprefix#files WHERE projectID = AND fileID = AND uploadedBy = DELETE FROM #variables.tableprefix#file_attach WHERE fileID = SELECT f.fileID,f.title,f.filetype,f.filename,f.serverfilename,f.filesize,f.uploaded,c.category FROM #variables.tableprefix#file_attach fa JOIN #variables.tableprefix#files f ON fa.fileID = f.fileID JOIN #variables.tableprefix#categories c on f.categoryID = c.categoryID WHERE f.projectID = AND fa.itemID = AND fa.type = INSERT INTO #variables.tableprefix#file_attach (itemID,fileID,type) VALUES (, , ) DELETE FROM #variables.tableprefix#file_attach WHERE itemID = AND type = SELECT type FROM #variables.tableprefix#file_attach WHERE fileID = SELECT c.categoryID, c.category, count(f.fileID) as numFiles FROM #variables.tableprefix#categories c left join #variables.tableprefix#files f ON c.categoryID = f.categoryID WHERE c.projectID = AND c.type = 'file' GROUP BY c.categoryID, c.category ORDER BY c.category