我有 3 个表 sc_user、sc_cube、sc_cube_sent
我想加入一个用户查询 (sc_user) 一个不同的随机消息/多维数据集 (来自 sc_cube),之前没有发送给该用户 (sc_cube_sent),因此结果集中的每一行都有一个不同的用户 ID和来自 sc_cube 的随机 cubeid,它不是 sc_cube_sent 的一部分,与那里关联的用户 ID。
我面临的问题是,我似乎无法在内部 On 子句中需要外部查询的 u.id 的情况下使用相关 ID。我需要评论部分才能使其正常工作。
# get one random idcube per user not already sent to that user
SELECT u.id, sub.idcube
FROM sc_user as u
LEFT JOIN (
SELECT c.idcube, sent.idreceiver FROM sc_cube c
LEFT JOIN sc_cube_sent sent ON ( c.idcube = sent.idcube /* AND sent.idreceiver = u.id <-- "unknown column u.id in on clause" */ )
WHERE sent.idcube IS NULL
ORDER BY RAND()
LIMIT 1
) as sub
ON 1
我添加了一些数据的 fiddle :http://sqlfiddle.com/#!9/7b0bc/1 应为用户 1 显示的新立方体 ID (sc_cube) 如下:2150、2151、2152、2153
编辑>>
我可以用另一个子查询而不是连接来完成它,但这会对性能产生巨大影响并且不可行(每个表上几千行的 30 秒+合理实现的键),所以我仍在寻找一个将解决方案与 JOIN 一起使用的方法。
SELECT
u.id,
(SELECT sc_cube.idcube
FROM sc_cube
WHERE NOT EXISTS(
SELECT sc_cube.idcube FROM sc_cube_sent WHERE sc_cube_sent.idcube = sc_cube.idcube AND sc_cube_sent.idreceiver = u.id
)
ORDER BY RAND() LIMIT 0,1
) as idcube
FROM sc_user u
最佳答案
如果无法对此进行测试,我会说您需要在子查询中包含您的 sc_user,因为您已经丢失了范围
LEFT JOIN
( SELECT c.idcube, sent.idreceiver
FROM sc_user u
JOIN sc_cube c ON c.whatever_your_join_column_is = u.whatever_your_join_column_is
LEFT JOIN sc_cube_sent sent ON ( c.idcube = sent.idcube AND sent.idreceiver = u.id )
WHERE sent.idcube IS NULL
ORDER BY RAND()
LIMIT 1
) sub
关于mysql - 嵌套加入子查询和失败关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30651147/