简体   繁体   English

从多个 MySQL 表中选择数据

[英]Select Data From Multiple MySQL Tables

Im searching for a function in MySQL in order to Select rows from multiple tables that have a similar name.我在 MySQL 中搜索一个函数,以便从多个具有相似名称的表中选择行。 For example: Proyect_1, Proyect_2, Proyect_3例如:Proyect_1、Proyect_2、Proyect_3

All of the tables have the same column names, the only difference between the tables is the table name.所有表都具有相同的列名,表之间的唯一区别是表名。 It starts with the prefix 'proyect'.它以前缀“项目”开头。 The issue is that the program doesn´t know how many 'proyect' tables there are, so i can´t make a list of them and select data like always问题是程序不知道有多少个“项目”表,所以我不能像往常一样列出它们并选择数据

I need something like this:我需要这样的东西:

SELECT mydata FROM TABLES LIKE 'Proyect_%';

Any ideas?有任何想法吗? Thanks!谢谢!

if you want to search for all tables with name like Proyect then you can get from MySQL information schema.如果要搜索名称为 Proyect 的所有表,则可以从 MySQL 信息模式中获取。

SELECT * FROM information_schema.tables 

From here you can find table by table name从这里您可以按表名查找表

To get all tables with a common prefix获取具有公共前缀的所有表

SHOW TABLES LIKE 'Proyect_%';

This will return rows of tables that matched the prefix.这将返回与前缀匹配的表行。 Example:例子:

Proyect_1
Proyect_2
Proyect_3

In PHP you can create a UNION query that will pick up the tables returned by the above query,PHP您可以创建一个UNION查询来获取上述查询返回的表,

$sql = "SHOW TABLES LIKE 'Proyect_%'";
$result = $conn->query($sql);

$dataQuery = array();
$query = "";
if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_array(MYSQLI_NUM)) {
     $dataQuery[] = "SELECT * FROM {$row[0]}";
  }
  $query = implode(' UNION ', $dataQuery);
}

echo $query;

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

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