简体   繁体   English

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

[英]Select random rows from one MYSQL table with join

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. 我想从一个表中选择随机行,然后从另一个表中加入我具有相同ID的该随机行。 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. 所以:我想要显示轨道ID的随机轨道->带有随机剪切,其中可以有很多,但我只想要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. 我现在正尝试进一步,并通过RAND()种子对其进行排序,因为我现在必须添加分页。 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;

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM