Question

I need to retrieve a random ID of a user which has in another table the avatar field not empty

SELECT userid FROM table1 WHERE EXISTS (SELECT 'avatar' FROM table2 WHERE avatar IS NOT NULL) ORDER BY RAND() LIMIT 1;

This query returns a result incorrect also showing me who has no avatar

Was it helpful?

Solution

I assume a table structure as follows:

table1 {
    userid primary key
    [...]
}

table2 {
    [...]
    userid foreign key
    avatar
}

The following SQL should work:

SELECT userid FROM table1 a
LEFT JOIN table2 b ON a.userid = b.userid
WHERE avatar IS NOT NULL
ORDER BY RAND() LIMIT 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top