Combine two word from a MySQL database at random

强颜欢笑 提交于 2021-02-08 02:56:27

问题


I have a database with nouns and adjectives for example:

id | type    | word  
-----------------------
1  | noun    | apple
2  | noun    | ball
3  | adj     | clammy
4  | noun    | keyboard
5  | adj     | bloody

ect...

I want to create one query what will grab 10 random adjectives and 10 random nouns and put them together.

Having trouble doing it, is this possible?

Thank you!


回答1:


You can get 10 random elements per type with queries like this:

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;

and then put them together in your PHP code, like so:

$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);

Please note that this code is not very safe (it makes the assumption that the second query always yields as least as many results as the first), but you get the idea.

Edit: Here's a single SQL query that should do it:

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;

EDIT: removed example



来源:https://stackoverflow.com/questions/4152765/combine-two-word-from-a-mysql-database-at-random

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!