MySQL Rand()不在子查询中?

时间:2015-09-20 12:23:56

标签: php mysql sql

我有一组需要播放的曲目, 数据库中有70个轨道,我的脚本需要生成一个新ID才能开始下一个轨道。

当前查询:( $ row ['v_artist']是当前正在播放的艺术家)

SELECT *
FROM t_tracks
WHERE v_artist NOT LIKE '%".$row['v_artist']."%'
ORDER BY RAND()
LIMIT 1;

现在我想为rand()添加一个子查询,以便它选择一个随机id,但不是从前50个(不是IN?)

子查询:

SELECT *
FROM `t_playlist`
ORDER BY pl_last_played DESC
LIMIT 50, 1

如何从t_tracks中获取t_playlist查询中不存在的随机ID?

1 个答案:

答案 0 :(得分:0)

从概念上讲,我认为你想要这个:

SELECT *
FROM t_tracks
WHERE v_artist NOT LIKE '%".$row['v_artist']."%' AND
      track_id NOT IN (SELECT track_id FROM t_playlist ORDER BY pl_last_played DESC LIMIT 50)
ORDER BY RAND()
LIMIT 1;

但是,MySQL在某些子查询中不允许LIMIT,因此请改用LEFT JOIN

SELECT t.*
FROM t_tracks t LEFT JOIN
     (SELECT track_id
      FROM t_playlist
      ORDER BY pl_last_played DESC
      LIMIT 50
     ) p
     ON t.track_id = p.track_id
WHERE t.v_artist NOT LIKE '%".$row['v_artist']."%' AND
      p.track_id IS NULL
ORDER BY RAND()
LIMIT 1;