(Before you mark this as duplicate, please read the question).
I have two different tables, Bot
and Switch
.
Bot
ID | Info | Active
------------------
0 | abc | 1
1 | def | 1
Switch
Date | Activated | BotID | User
-------------------------------------
2020-01-01 | 1 | 0 | John
2020-01-02 | 0 | 0 | John
For each bot, I would like to retrieve its latest status, which means: for each bot, I would like to know whether latest row's Activated
field was 1
or 0
. In order to return a result for those bots who do not have an entry in the Switch
table, I tried to use a LEFT JOIN
statement. Here is the query:
SELECT IFNULL(x.Activated, 0) AS Following, b.ID, b.Info
FROM bot b
LEFT JOIN (
SELECT *
FROM switch s1
WHERE s1.Date IN (
SELECT MAX(s.Date)
FROM switch s
WHERE s.User = 'SomeUsername'
GROUP BY s.Bot
)
) AS x ON x.BotID = b.ID
WHERE b.Active = 1
My expected result is:
Following | ID | Info
---------------------
0 | 0 | abc
0 | 1 | def
Point is that I'm not getting all rows, instead this query just return a single row:
Following | ID | Info
---------------------
0 | 0 | abc
This is strange since I'm using the LEFT JOIN
. In order to understand what's going on, I separately ran
SELECT *
FROM bot
and
SELECT *
FROM switch s1
WHERE s1.Date IN (
SELECT MAX(s.Date)
FROM switch s
WHERE s.User = 'SomeUsername'
GROUP BY s.Bot
)
Of course, the first query returns:
ID | Info
---------
0 | abc
1 | def
While the second one returns:
Date | Activated | BotID | User
-------------------------------------
2020-01-02 | 0 | 0 | John
I really cannot understand why the LEFT JOIN
is not keeping both Bot
rows. I checked this question, but I'm not using any outer WHERE
so it's not my case.
Thanks in advance!