我想创建一个查询,从一个表中获取名称,然后将其与其他表联系起来,按字母顺序为字母表中的每个字母排序,然后在一个查询中限制为每个字母的n个结果。
所以我不会为每个字母运行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个结果。 有没有办法做到这一点?
感谢。
答案 0 :(得分:0)
我认为sql不是那么灵活 - 但我不确定。你必须为此编写存储过程。
首先创建一个生成此序列的序列:A,B,C,...,Z,A,B,C,...,Z,A,B,C ...... 我们称之为magic_sequence。
然后创建一个临时表,其中包含一个列,init,从魔术序列播种,另一个,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
如果需要,您还必须随机化。