I'm writing MySQL to get all unique IDs from all tables in a database.
The database has tables like record_20181201, record_20181202, ...
The tables are automatically generated based on date (all tables have the same schema, and one column name is visitorId).
The SQL query I made is like,
SELECT UNIQUE(visitorId) FROM databaseName.record_20181201;
I can only query one table at a time using this..
Is there a way to query all tables in the database and select all unique visitorIds there?
SELECT DISTINCT VisitorID FROM DBName.Table1
UNION
SELECT DISTINCT VisitorID FROM DBName.Table2
UNION
SELECT DISTINCT VisitorID FROM DBName.Table3
Try this!!!!!!Hope this helps..
You could generate a query string with UNION's from the INFORMATION_SCHEMA.
Then run that query, or put it in a view.
A UNION
will return a unique combined result of the unioned queries.
While a UNION ALL
would just stick the results together.
SELECT GROUP_CONCAT(Qry ORDER BY TblSchema, TblName SEPARATOR ' UNION ')
FROM
(
SELECT
TABLE_SCHEMA as TblSchema,
TABLE_NAME as TblName,
CONCAT('select visitorId from ',TABLE_SCHEMA,'.',TABLE_NAME,'\r\n') as Qry
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'record_201812%'
AND COLUMN_NAME = 'visitorId'
) Q;
Run below query you will get a single query that will give unique visitorId from all table.
SELECT
CONCAT('SELECT DISTINCT visitorId FROM (',
REPLACE(query_string, ',', ' UNION '),
') union_table') AS final_query
FROM
(SELECT
CONCAT(GROUP_CONCAT('SELECT visitorId FROM ', table_name)) AS query_string
FROM
information_schema.tables
WHERE
table_name LIKE 'record_%') table_a;
you will get below query that will fetch unique visitorId from all tables.
SELECT DISTINCT
visitorId
FROM
(
SELECT visitorId FROM record_20181201
UNION
SELECT visitorId FROM record_20181202
UNION
SELECT visitorId FROM record_20181203
) union_table
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.