duanmei1930 2017-09-14 11:06
浏览 89
已采纳

使用join从一个MYSQL表中选择随机行

Afternoon folks,

I have had a good dig around and can't find the answer, so a good time to ask!

I'd like to select random rows from one table and then join into this random rows from another table where the ID that I have is the same. It would also be great to only select where I have an entry in the second table. I have tried all manner of sub-queries but am getting a bit lost. An inner join as read will do it but again with the randomness of it all!! Grrr...

SELECT
  tracks.track_id,
  cuttings.square_cutting,
  cuttings.cutting_2,
  cuttings.cutting_3,
  cuttings.blog_text 
FROM tbl_tracks tracks,
(SELECT 
    square_cutting,
    cutting_2,
    cutting_3,
    blog_text 
  FROM
    tbl_cuttings
  WHERE track_id = tracks.track_id <-- wont find it, obviously!!
  ORDER BY RAND() 
  LIMIT 1) cuttings
WHERE tracks.active = '1' ORDER BY RAND()

Thanks in advance for any help.

So: I'd like random tracks showing track id -> with random cuttings, of which there can be many but I just want 1.

It would then be ideal to only show a result if there is a cutting associated with that track.

Hope that helps.

I'm now trying to go a step further with this and order this by a RAND() seed as I'm now having to add in pagination. Only problem is that its not giving me back the same random list due to a given seed. Any Ideas?

SELECT
  tracks.track_id,
  cuttings.square_cutting,
  cuttings.cutting_2,
  cuttings.cutting_3,
  cuttings.blog_text
FROM tbl_tracks tracks
INNER JOIN
  (SELECT track_id,
    square_cutting,
    cutting_2,
    cutting_3,
    blog_text
    FROM
    tbl_cuttings
ORDER BY RAND()) cuttings ON tracks.track_id = cuttings.track_id
WHERE tracks.active = '1'
ORDER BY RAND(1)
LIMIT 0,4;
  • 写回答

1条回答 默认 最新

  • duanli0687 2017-09-14 11:12
    关注

    you could use an inner join

      SELECT
        tracks.track_id,
        cuttings.square_cutting,
        cuttings.cutting_2,
        cuttings.cutting_3,
        cuttings.blog_text 
      FROM tbl_tracks tracks
      INNER JOIN 
      (SELECT track_id,
          square_cutting,
          cutting_2,
          cutting_3,
          blog_text 
        FROM
          tbl_cuttings
         ORDER BY RAND() 
        LIMIT 1) cuttings on cuttings.track_id = tracks.track_id
      WHERE tracks.active = '1' 
      ORDER BY RAND()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载