dongwu9972 2010-11-11 09:04
浏览 191
已采纳

从MySQL数据库中随机组合两个单词

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条回答 默认 最新

  • douxing8323 2010-11-11 09:09
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序