如何动态UNION ALL所有含FirstName列的表以实现高频FirstName统计?
Great question! To make your query dynamically include all tables with a FirstName column without manual updates, you'll need to use dynamic SQL—this lets you build your query string on the fly using metadata from information_schema.
Here's how to pull it off, with examples for common databases like MySQL and SQL Server:
Step-by-Step Explanation
- Fetch all target tables: Use your existing query to get every table that has a
FirstNamecolumn. - Build the dynamic UNION ALL clause: Combine these tables into a single string of
SELECT FirstName FROM [table]statements joined byUNION ALL. - Inject this into your original query logic: Wrap the dynamic clause into your CTE structure, then execute the final assembled SQL.
Example for MySQL
SET @sql = NULL; -- Assemble all the SELECT statements for tables with FirstName SELECT GROUP_CONCAT( -- Use backticks to handle table names with spaces/reserved words CONCAT('SELECT FirstName FROM `', table_name, '`') SEPARATOR ' UNION ALL ' ) INTO @sql FROM information_schema.columns WHERE column_name = 'FirstName'; -- Build the full query with your original CTE logic (optimized) SET @final_sql = CONCAT(' WITH AllFirstNames AS (', @sql, '), FirstNameOccurrences AS ( SELECT FirstName, COUNT(*) AS Occurrences FROM AllFirstNames GROUP BY FirstName ) SELECT FirstName AS MostOccurringFirstNames FROM FirstNameOccurrences WHERE Occurrences = (SELECT MAX(Occurrences) FROM FirstNameOccurrences); '); -- Execute the dynamic SQL PREPARE stmt FROM @final_sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
Example for SQL Server
DECLARE @sql NVARCHAR(MAX); -- Use STRING_AGG to build the UNION ALL clause (SQL Server 2017+) SELECT @sql = STRING_AGG( -- QUOTENAME handles special characters/reserved words in table names CONCAT('SELECT FirstName FROM ', QUOTENAME(table_name)), ' UNION ALL ' ) FROM information_schema.columns WHERE column_name = 'FirstName'; -- Assemble the full query DECLARE @final_sql NVARCHAR(MAX) = CONCAT(N' WITH AllFirstNames AS (', @sql, N'), FirstNameOccurrences AS ( SELECT FirstName, COUNT(*) AS Occurrences FROM AllFirstNames GROUP BY FirstName ) SELECT FirstName AS MostOccurringFirstNames FROM FirstNameOccurrences WHERE Occurrences = (SELECT MAX(Occurrences) FROM FirstNameOccurrences); '); -- Run the dynamic query EXEC sp_executesql @final_sql;
Key Notes
- Permissions: Make sure the user running this query has read access to
information_schema.columns. - Special Table Names: Always wrap table names in backticks (MySQL) or
QUOTENAME()(SQL Server) to avoid errors if tables have spaces, hyphens, or match SQL reserved words. - Efficiency: I simplified your original final
SELECT—no need to re-queryAllFirstNames; you can directly pull fromFirstNameOccurrencessince it already has the grouped counts.
Now whenever you add a new table with a FirstName column, this query will automatically include it without any manual edits!
内容的提问来源于stack exchange,提问作者thomasdowell
相关产品推荐
相关产品推荐

