So I have a fairly complex query right now that goes something like this:
SELECT keywords.id as keyword_id,
keywords.keyword as keyword,
i.id as position_id,
i.position as position,
i.created_at as created_at
FROM keywords
LEFT JOIN positions i
ON i.keyword_id = keywords.id
AND i.id >= COALESCE((
SELECT i1.id
FROM positions i1
WHERE i1.keyword_id = keywords.id
ORDER BY i1.id DESC
LIMIT 1
OFFSET 1
), 0)
WHERE keywords.website_id = ?
ORDER BY keywords.keyword ASC, i.id ASC', [$this->id]);
So now I'm trying to add additional data to the query. I need the oldest row (based on created_at column) in either positions
or position_backups
table. I would need to check for oldest row in position_backups
first and if it's not found, then get oldest row in positions
for that keyword_id
.
Can anyone give me any pointers in how to get this done? I've searched a lot but have not quite found what I'm looking for.
This is what I have so far. I'm not sure if it does exactly what I need as I need to test it more. Any comments or suggestions appreciated.
SELECT keywords.id as keyword_id,
keywords.keyword as keyword,
i.id as position_id,
i.position as position,
i.url as url,
i.created_at as created_at,
ifnull ((select position from position_backups WHERE keyword_id = keywords.id ORDER BY id ASC LIMIT 1), (select position from positions WHERE keyword_id = keywords.id ORDER BY id ASC LIMIT 1)) as first_position
FROM keywords
LEFT JOIN positions i
ON i.keyword_id = keywords.id
AND i.id >= COALESCE((
SELECT i1.id
FROM positions i1
WHERE i1.keyword_id = keywords.id
ORDER BY i1.id DESC
LIMIT 1
OFFSET 1
), 0)
WHERE keywords.website_id = 20
ORDER BY keywords.keyword ASC, i.id ASC