简体   繁体   English

如何自动从多个表中选择一列

[英]How to automate selection of a column from multiple tables

I have several tables at least 26 ... i'm trying to select a column from all tables and displaying them as one我有几个表至少 26 ......我试图从所有表中选择一列并将它们显示为一个

i tried this :我试过这个:

(SELECT col1,col2,col3,col4 FROM table1 ORDER BY col1 DESC LIMIT 1) UNION (SELECT col1,col2,col3,col4 FROM table2 ORDER BY col1 DESC LIMIT 1) (SELECT col1,col2,col3,col4 FROM table1 ORDER BY col1 DESC LIMIT 1) UNION (SELECT col1,col2,col3,col4 FROM table2 ORDER BY col1 DESC LIMIT 1)

this works but i have to copy and paste a bunch of times depending on how many number of tables i have which isn't very effective .这有效,但我必须根据我拥有的表格数量进行多次复制和粘贴,这不是很有效。 Please Help -- i just started learning mysql and i'm stuck trying to fix this.请帮助——我刚开始学习 mysql,我一直在努力解决这个问题。

You can do it by using a cursor inside a stored procedure, like this:您可以通过在存储过程中使用游标来实现,如下所示:

BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE tablename VARCHAR(100);
  DECLARE tableschema VARCHAR(100);
  DECLARE sql_union_tables TEXT;
  DECLARE tables_cursor CURSOR FOR SELECT TABLE_NAME, TABLE_SCHEMA FROM information_schema.`TABLES` WHERE TABLE_SCHEMA = 'DbInscripciones' AND TABLE_NAME LIKE 'TblFaltasA%';
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN tables_cursor;
  
  SET sql_union_tables = '';

  read_loop: LOOP
    FETCH tables_cursor INTO tablename, tableschema;
    IF done THEN
      LEAVE read_loop;
    END IF;
    IF sql_union_tables = '' THEN
      SET sql_union_tables = CONCAT('(SELECT numcontrol FROM ', tableschema, '.', tablename, ' LIMIT 1)');
    ELSE
      SET sql_union_tables = CONCAT(sql_union_tables, ' UNION ALL (SELECT numcontrol FROM ', tableschema, '.', tablename, ' LIMIT 1)');
    END IF;
  END LOOP;

  CLOSE tables_cursor;
  
  SET sql_union_tables = CONCAT(sql_union_tables, ';');
  
  PREPARE stmt FROM sql_union_tables;
  EXECUTE stmt;
  
  SELECT sql_union_tables;
END

Let's explain this by parts.让我们分部分解释这一点。 You get a list of desired table names by querying the information_schema database, and the tables_cursor cursor will allow you to iterate over that table list.您可以通过查询information_schema数据库获得所需表名的列表, tables_cursor游标将允许您遍历该表列表。

In the iteration part you construct a query using the tables obtained from the cursor query and save it in sql_union_tables .在迭代部分,您使用从游标查询中获得的表构造一个查询并将其保存在sql_union_tables

After you finish constructing the query you execute it with the PREPARE and EXECUTE statements and also return the resulting query (last line).构建完查询后,使用PREPAREEXECUTE语句执行它,并返回结果查询(最后一行)。

This stored procedures assumes you have the same columns in your tables.此存储过程假定您的表中有相同的列。 If your columns vary for each table you'll have to implement some logic to deal with that.如果每个表的列都不同,则必须实现一些逻辑来处理它。

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

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