2014-07-17 90 views
0

我想創建一個查詢,它將從一個表中獲取名稱,然後與其他人結合,按字母順序排列字母表中的每個字母,然後限制爲每個字母的n個結果一個查詢中的字母。MySQL按字母表限制每個字母的n個結果的名稱組

所以我不wan't運行26個查詢像每一個字母:

SELECT CONCAT_WS(' ',first_name,last_name) AS name FROM encyclopedia WHERE name LIKE "A%" ORDER BY rand() LIMIT 4 
SELECT CONCAT_WS(' ',first_name,last_name) AS name FROM encyclopedia WHERE name LIKE "B%" ORDER BY rand() LIMIT 4 
SELECT CONCAT_WS(' ',first_name,last_name) AS name FROM encyclopedia WHERE name LIKE "C%" ORDER BY rand() LIMIT 4 

現在我有:

SELECT 
     e.id, 
     CONCAT_WS(' ',first_name,last_name) AS name, 
     sg.name AS sub_name, 
     sg.id AS sub_id 
     FROM (SELECT id,first_name,last_name FROM encyclopedia ORDER BY RAND() LIMIT 4) AS e 
     LEFT JOIN encyclopedia_subgenres esub 
     ON (e.id = esub.enc_id) 
     LEFT JOIN subgenres sg 
     ON (esub.subgenre_id = sg.id) 
     ORDER BY name 

然後從PHP創建從結果數組:

Array 
(
    [b] => Array 
     (
      [2] => Array 
       (
        [name] => B Style 
        [genres] => Array 
         (
          [26] => Classic 
          [27] => X 
          [29] => Y 
         ) 

       ) 

      [7] => Array 
       (
        [name] => Beyonce Giselle Knowles 
        [genres] => Array 
         (
          [32] => Pop 
         ) 

       ) 

     ) 

    [i] => Array 
     (
      [1] => Array 
       (
        [name] => Ivan D 
        [genres] => Array 
         (
          [27] => R&B 
          [2] => Jazz 
         ) 

       ) 

     ) 

    [m] => Array 
     (
      [3] => Array 
       (
        [name] => Maria T 
        [genres] => Array 
         (
          [26] => Classical 
          [27] => Pop 
          [28] => Dance 
         ) 

       ) 

     ) 

) 

但事實是,它限制了我只有4個隨機結果可以是4對相同字母或任何COMBI國家。 有沒有辦法做到這一點?

謝謝。

回答

0

我認爲sql沒那麼靈活 - 但我不確定。你必須爲此編寫存儲過程。

首先創建一個生成此序列的程序:A,B,C,...,Z,A,B,C,...,Z,A,B,C ...... 讓我們稱它爲magic_sequence 。

然後創建一個臨時表,其中有一列init,從magic序列中另一個count_down,等於4.它應該有26行。我們稱之爲init_table;

然後即寫另一個函數acceptance_test是

- take a string S with 
- decrease count_down of the corresponding row in init_table 
- return true if count_down > = 0; otherwise false 

現在有一個這樣的查詢:

SELECT CONCAT_WS(' ',first_name,last_name) AS name FROM encyclopedia WHERE acceptance_test(name) LIMIT 4*26 

您也可以隨機,如果你想要的。

相關問題