guido, thanks. You misunderstand my last posts.
In fact, your example query has led to a visually noticeable performance increase in retrieving the needed records -- THANK YOU!
Yes, your first query does pull the latest record from each table; I agree. That clarified, I was referring to the next query I posted on this thread (the post at 22:53pm, which was a variation on your original query).
You're also right in that this was not the original question... but as it was something very similar that I ALSO needed to achieve, I thought I'd post the other query as well, so that both queries could be shown -- or shot down -- here. It's always good to find relatively like things together.
Anyway, here's the final 2 queries that I'm using, and if you can see a better way still, I'm happy to hear your advice! Did my best to format the queries, sorry they're not perfect.
Code:
// Get latest record from each of X tables in a single query.
(SELECT
1 AS difficulty,
level1.*
FROM level1
ORDER BY id DESC
LIMIT 1)
UNION
(SELECT
2 AS difficulty,
level2.*
FROM level2
ORDER BY id DESC
LIMIT 1)
UNION
...etc...
(SELECT
8 AS difficulty,
level8.*
FROM level8
ORDER BY id DESC
LIMIT 1)
ORDER BY difficulty;
Code:
// Get a single random record from each of X tables in a single query.
(SELECT
1 AS sort_col,
t1.*
FROM t1
ORDER BY RAND()
LIMIT 1)
UNION
(SELECT
2 AS sort_col,
t2.*
FROM t2
ORDER BY RAND()
LIMIT 1)
UNION
...etc...
(SELECT
8 AS sort_col,
t8.*
FROM t8
ORDER BY RAND()
LIMIT 1)
ORDER BY sort_col;
Bookmarks