2015-08-14 102 views
1

我想創建一個查詢,從我的表中爲每個parent_id選擇2個隨機行。 目前我的查詢總是返回每個parent_id的前2個id。 (例如:parent_id = 1,2)。MYSQL - 查詢選擇有限制的父母編號的隨機行

我的表目前如下:

id, title , parent_id 
1, Title1 ,   1 
2, Title2 ,   1 
3, Title3 ,   1 
4, Title4 ,   2 
5, Title5 ,   2 
6, Title6 ,   2 
7, Title7 ,   2 
8, Title8 ,   3 
9, Title9 ,   3 
10, Title10,   3 

我當前的查詢是:

SELECT id,title,parent_id, rn 
FROM (SELECT (@rn := if(@parent_id = parent_id, @rn + 1, 
         if(@parent_id := parent_id, 1, 1) 
         ) 
      ) as rn, 
      meals.* 
     FROM meals CROSS JOIN 
      (SELECT @rn := 0, @parent_id := '') params 
     ORDER BY rand() 
    ) meals 
WHERE rn <= 2 
ORDER BY id ASC 

我想我的結果更改每個查詢,以便例如一個結果將返回id爲1,3的parent_id = 1和一個會返回2,3等等...

回答

1

嘗試order by rand()條款移動到它自己的派生表

SELECT id,title,parent_id, rn 
FROM (SELECT (@rn := if(@parent_id = parent_id, @rn + 1, 
         if(@parent_id := parent_id, 1, 1) 
         ) 
      ) as rn, 
      t1.* 
     FROM (SELECT * FROM meals CROSS JOIN 
      (SELECT @rn := 0, @parent_id := '') params 
      ORDER BY rand()) t1 
     ORDER BY parent_id 
    ) meals 
WHERE rn <= 2 
ORDER BY id ASC 

http://sqlfiddle.com/#!9/3310f/1

+1

作品像一個魅力!謝謝!! – nimi

0

我認爲你只需要添加parent_id到在order by

SELECT id, title, parent_id, rn 
FROM (SELECT (@rn := if(@parent_id = parent_id, @rn + 1, 
         if(@parent_id := parent_id, 1, 1) 
         ) 
      ) as rn, 
      meals.* 
     FROM meals CROSS JOIN 
      (SELECT @rn := 0, @parent_id := -1) params 
     ORDER BY parent_id, rand() 
    ) meals 
WHERE rn <= 2 
ORDER BY id ASC; 

而且,如果parent_id是一個數字,沒有任何理由讓@parent_id的字符串。

+0

仍然沒有工作。我一直得到相同的排順序 – nimi