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國家。 有沒有辦法做到這一點?
謝謝。