我有一个名词和形容词的数据库,例如:
id | type | word
-----------------------
1 | noun | apple
2 | noun | ball
3 | adj | clammy
4 | noun | keyboard
5 | adj | bloody
等...
我想创建一个查询,它会抓取10个随机形容词和10个随机名词并将它们放在一起。
无法做到这一点,这可能吗?
谢谢!
答案 0 :(得分:4)
每种类型可以获得10个随机元素,如下所示:
select word from YOUR_TABLE where type = 'noun' order by rand() limit 10;
select word from YOUR_TABLE where type = 'adj' order by rand() limit 10;
然后将它们放在PHP代码中,如下所示:
$phrases = array();
$adj_result = mysql_query("SELECT word FROM words WHERE type = 'adj' ORDER BY RAND() LIMIT 10");
$noun_result = mysql_query("SELECT word FROM words WHERE type = 'noun' ORDER BY RAND() LIMIT 10");
while($adj_row = mysql_fetch_assoc($adj_result)) {
$noun_row = mysql_fetch_assoc($noun_result);
$phrases[$adj_row['word']] = $noun_row['word'];
}
print_r($phrases);
请注意,此代码不是很安全(它假设第二个查询的结果总是少于第一个),但是你明白了。
编辑:这是一个应该执行的SQL查询:
select t1.word, t2.word
from
((select word from YOURTABLE where type = 'adj' order by rand()) as t1),
((select word from YOURTABLE where type = 'noun' order by rand()) as t2)
order by rand()
limit 10;
编辑:删除示例