I have two tables:
USER:
userID | uName |
-----------------
1 | John
2 | Bohn
3 | Kohn
4 | Lohn
5 | Zohn
6 | Rohn
IMAGES:
imageID | url | userID
----------------------
1 | x | 2
2 | x | 2
3 | x | 1
4 | x | 3
5 | x | 3
6 | x | 3
As you can see there is USER database which connects to IMAGES database by userID.
There is only one unique user row but there can be more than one image per user.
What i want is to fetch ONE RANDOM user from database and all of his images. Condition is that user should not be selected if he has no images.
Can you help me build ONE mysql query to achieve that?
P.S. It doesnt matter if user data duplicates (because of multiple image rows), there is only one user in resultset anyways.
First,
INNER JOINboth tables, to exclude users that don’t have any images; then,ORDER BY RAND(), to randomize the resultset; finally, select the first row to obtain a randomuserId:DEMO.
EDIT: To select all images from a random user, use the following:
DEMO.