I am trying to find the max date across multiple columns (in multiple tables). I have an SQL query that I think is almost workable, but am having a hard time debugging it. The problem is that it never returns anything. Any ideas on what I'm doing incorrectly? I don't get any errors, just an empty row "maxdate."
Here's my query:
SELECT
(
SELECT MAX(dates) FROM
(
SELECT dates = t1.UpdateDate
UNION ALL
SELECT dates = t2.UpdateDate
UNION ALL
SELECT dates = t3.UpdateDate
UNION ALL
SELECT dates = t4.UpdateDate
) as dateAcrossColumns
) as maxdate
FROM table1 as t1
join table2 as t2 on t1.ID = t2.ID
join table3 as t3 on t1.ID = t3.ID
join table4 as t4 on t1.ID = t4.ID
join table5 as t5 on t1.Status = t5.Status
WHERE t1.id = @param and t5.status <> 3
Cant think of a simpler way of doing this :)
If it's possible for any of the tables to not have any rows for the given @param, the (inner) joins will filter out all of the other tables.
Try unioning the dates and get the max of the unions
I was trying to solve a similar problem to find the last modified date across a set of joined tables in MySQL. The following worked for me using a combination of
GREATEST
andMAX
:First join you join to table 2 using table 1's ID and table 3's ID. I presume you mean table 1's ID and table 2's ID?
Should be:
Now that this has been changed;
I tried your query and it works fine, are you sure that your joins are bringing back any rows? To test it replace your
SELECT
statement withSELECT *
, if you get no rows back then they are being filtered out somewhere in your joins /WHERE
.