I've got a problem with a correlation inside a sub-query.
I have 2 tables :
- table1 : contains "groups" with a groupid
, a groupename
and a categoryid
- table2 : tells which people is member of which group (with fields: userid
, groupid
)
I would like to ask my database to give me :
all groups from a specific "category
" with for each of them :
- the groupid
, the groupname
- and a random selection of 4 members for each group
I followed the question MySQL select 10 random rows from 600K rows fast to generate 4 random members of a specific group.
It works well if I run the query separately.
but if I try to incorporate my sub-query inside my "general query" :
SELECT
g.groupid, g.groupname,
(
SELECT GROUP_CONCAT(table2.userid SEPARATOR ",")
FROM table2, (
SELECT userid AS uid
FROM table2
WHERE table2.groupid = g.groupid
ORDER BY RAND( )
LIMIT 4
) tmp
WHERE table2.userid = tmp.uid
) AS randomusers
FROM table1 AS g WHERE g.categoryid = ?
... I get a "Unknown column 'g.groupid' in 'where clause'" ERROR.
I tried to pass the subquery into a LEFT JOIN
but I can't figure out how to do it properly as each of my attempts are unsuccessful.
Any help on this? Thanks :)