简体   繁体   中英

Select query for multiple tables

I have tables A01, B01, C01 and so on... all with identical structure.

+----+-----+
| ID | val |
+----+-----+
|  1 | a   |
|  2 | b   |
+----+-----+

+----+-----+
| id | val |
+----+-----+
|  1 | c   |
|  2 | d   |
+----+-----+

+----+-----+
| id | val |
+----+-----+
|  1 | e   |
|  2 | f   |
+----+-----+

Is it possible to have a query that displays the "val" column from all tables ?

Also so that if a new tables is created the query should not be changed.

I am going to run this on a PHP webpage.

SQLFiddle

SELECT t1.val
  FROM table1 AS t1
UNION
  SELECT t2.val FROM table2 AS t2
UNION
  SELECT t3.val FROM table3 AS t3

you cant do new tables in mysql . you must define them . for the given tables you can do this

   select val from `A01`
   union all
   select val from `B01`
   union all
   select val from `C01`

demo

Create a view with union or union all clause with all your required tables. If you create a table in future , just alter the view to include that table as well.

CREATE VIEW AS MYVIEW
SELECT VAL FROM A01 UNION ALL
SELECT VAL FROM B01...

Always use same query to get data:

SELECT VAL FROM MYVIEW

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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