SQL选择随机行时加入帮助

时间:2011-12-07 18:46:58

标签: mysql sql join random

我有2张桌子; '群体'和'价值'。我试图从值表中选择一个随机行,其中values.groupid = groups.id

我的查询是:

SELECT *
FROM groups as g
inner JOIN
(
SELECT * FROM values as v WHERE v.groupid = g.id ORDER BY RAND() LIMIT 1
) AS rv ON rv.groupid = g.id

v似乎无法访问g我该如何解决这个问题?关于随机,我只设法得到限制1解决方案工作,因为可能有删除value.id的,它是小表(只有最多200行)。如果我只使用join on,并且在join中没有where子句,它将从任何组中选择随机值,或者不返回任何内容。有谁可以帮助我?

编辑: 这不会工作,因为我这次不能从外面访问v

SELECT g.*
,(SELECT * FROM v ORDER BY RAND() LIMIT 1)
FROM groups AS g
JOIN
(
  SELECT * FROM values
) AS v ON v.groupid = g.id

我看到许多其他问题非常相似但是,实际上没有人试图为每个组的值实现加入..如果我错过了一个请提及我将删除问题,我会不断看别人但是与此同时,我仍然需要帮助。谢谢

2 个答案:

答案 0 :(得分:4)

我总是避免在SQL中使用ORDER BY RAND(),除非您的数据集非常小,否则会导致糟糕的性能。如果您的数据集很小,那么最好还是将所有行添加到您的应用程序中并选择随机行。

这是我刚刚测试过的解决方案,它可以从每个组中选择一个随机行:

SELECT g.*, v.*
FROM Groups AS g
INNER JOIN (
  SELECT groupid, COUNT(*) AS c, 1+FLOOR(RAND()*COUNT(*)) AS random 
  FROM `Values` GROUP BY groupid
) AS c ON g.id = c.groupid
INNER JOIN (SELECT @g:=0, @r:=0) AS init
INNER JOIN (
  SELECT IF(groupid<>@g, @r:=1, @r:=@r+1) AS rank, @g:=groupid AS groupid, value
  FROM `Values`
  ORDER BY groupid
) AS v ON g.id = v.groupid AND c.random = v.rank

答案 1 :(得分:1)

SELECT u.login, a.filename FROM users u 
JOIN (SELECT filename, user_id, id AS rand_id FROM assets ORDER BY RAND()) a
ON u.id = a.user_id 
WHERE a.filename IS NOT NULL
GROUP BY user_id
ORDER BY u.login;