Nick Nick - 3 months ago 10
MySQL Question

SQL Query select max value unless not null from two tables with intersection

Tables:

Files
-------------------
id | revision
-------------------
1 | 0
1 | 1
1 | 2
2 | 0
2 | 1

Folders
-----------------
id | name
-----------------
1 | FooBar

Shares
--------------------------------
id | folderId | fileId | fileRev
--------------------------------
1 | 1 | 1 | null
2 | 1 | 2 | 0


The output I am expecting:

fileId | revision
------------------
1 | 2
2 | 0


I want to be able to take the information based on the Shares table and if the file revision is NULL, return the record of that file with the highest revision. If fileRev is not null, return the file record that corresponds with that revision.

I've been able to replicate it like so:

SELECT f.id, max(f.rev) as rev
FROM files f
INNER JOIN shares s ON s.fileId = f.id
WHERE s.fileRev IS NULL AND s.folderId = 1
GROUP BY f.id
UNION
SELECT f.id, f.rev as rev
FROM files f
INNER JOIN shares s ON s.fileId = f.id AND f.rev = s.fileRev
WHERE s.fileRev IS NOT NULL AND s.folderId = 1


How can I do this with a more optimized query? Possibly without a union?

Answer

I think this should work, hard to test without the database available.

IFNULL returns either shares.fileRev if it's not null, and if it is it returns files.rev

SELECT files.id,
       MAX(IFNULL(shares.fileRev, files.rev)) as rev
FROM files
JOIN shares ON shares.fileId = files.id
WHERE shares.folderId = 1
GROUP BY files.id