从许多post_ids中选择MySQL中的1个随机项

时间:2014-04-13 02:58:59

标签: php mysql sql pdo

我有一个数据库,其布局如下:

Array
(
    [0] => Array
        (
            [id] => 23
            [post_id] => 9480
            [title] => This is numero uno
        )

    [1] => Array
        (
            [id] => 25
            [post_id] => 9480
            [title] => I like food
        )

    [2] => Array
        (
            [id] => 26
            [post_id] => 9480
            [title] => Oranges!
        )

    [3] => Array
        (
            [id] => 28
            [post_id] => 9476
            [title] => The quick brown fox
        )

    [4] => Array
        (
            [id] => 29
            [post_id] => 9476
            [title] => jumped!
        )

)

请注意post_id在某些行上可以相同。这基本上是属于单个帖子的几个标题变体。

我想做的是在给出post_id

的ID数组时,使用MySQL随机选择一个标题

所以输出可能是这样的(来自上面的输入):

9480 - 25 - I like food
9476 - 28 - The quick brown fox

其中每个都是从post_id s的子集中随机选择的。

这是我到目前为止所做的......并不多:/

SELECT `id`, `post_id`, `title` FROM `headlines` WHERE `post_id` IN(9480,9476)

2 个答案:

答案 0 :(得分:2)

按rand()排序,然后将1限制为每个OP请求获得一个..请参阅工作FIDDLE

SELECT
    mt.id, 
    mt.post_id, 
    mt.title
FROM (
  SELECT
  DISTINCT mt1.post_id AS my_post_id,
     (
       SELECT
         tttt.id AS m_id
       FROM myTable tttt
       WHERE tttt.post_id = my_post_id
       ORDER BY rand()
       LIMIT 1
     ) AS t
  FROM myTable mt1
  GROUP BY mt1.post_id
) AS tt
JOIN myTable mt ON mt.id = t
GROUP BY mt.post_id

答案 1 :(得分:0)

ORDER BY RAND()就是你想要的。

SELECT `id`, `post_id`, `title`
FROM `headlines`
WHERE `post_id` IN(9480,9476)
ORDER BY RAND()
LIMIT 1