简体   繁体   English

MySQL从多个相同的表中选择并使用php随机显示结果

[英]MySQL select from multiple identical tables and display results randomly with php

Hello I would like to query multiple identical tables in my db which has different prefixes and than display the results randomly but somehow I need to track the origin of the item and I couldn't figure out how 您好,我想在我的数据库中查询多个相同的表,这些表具有不同的前缀,而不是随机显示结果,但是以某种方式我需要跟踪项目的来源,但我不知道如何

I do the query like this because I don't have access to information_schema 我这样查询,因为我无权访问information_schema

$query = "SHOW TABLES FROM mydb WHERE RIGHT( tables_in_mydb, 5 ) = 'table'";
$res = mysql_query($query);
$num = mysql_num_rows($res);

while($row = mysql_fetch_row($res)) {

$numbers = explode('_', $row[0]);

  if($num > 0) {
    $q = "SELECT `this`, `that`, `something` FROM ".$numbers[0]."_idetinticaltables"; // :)
    $r = mysql_query($q);
    while($c = mysql_fetch_array($r)) {
       /*display the results randomly with an identifier where the come from*/
    }
  }
}

您可以使用ORDER BY RAND()对其进行随机排序

$aa=array()   
while($c = mysql_fetch_array($r)) 
{
   /*display the results randomly with an identifier where the come from*/
   $aa[]=$c;
}
echo $aa; // print "Array"

The following might work: 以下可能有效:

  1. Get the list of the tables you're interested in. You already do that. 获取您感兴趣的表的列表。您已经完成了。
  2. Create a UNION of multiple SELECT statements . 创建包含多个SELECT语句UNION Each SELECT statement differs for the table being selected from and you add a column set to the name of the table (so you can identify it later): 每个SELECT语句对于要从中SELECT表有所不同,并且您在表名中添加了一个列集(以便以后可以识别它):

     (SELECT *, TABLENAME = 'first_name_of_table' FROM first_name_of_table ...) UNION (SELECT *, TABLENAME = 'second_name_of_table' FROM second_name_of_table ...) UNION ... ORDER BY RAND() LIMIT 10; 
  3. Because it is a UNION you can randomize the whole order then. 因为它是一个UNION您可以将整个顺序随机化。 See How can i optimize MySQL's ORDER BY RAND() function? 请参阅如何优化MySQL的ORDER BY RAND()函数? because it is not that trivial to do well, the example above is only to have an ORDER BY and LIMIT clause placed there. 因为做得不好并不是一件容易的事,所以上面的示例只是在其中放置了ORDER BYLIMIT子句。 With many entries in your tables, it will kill your server. 表中有许多条目,它将杀死您的服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM