0

I have a lot of tables with the same _ips endings. Example:

first-domain.com_ips
secons-domain.com_ips
...

I'm trying to get UNION result table which will contains all rows from all _ips tables. For this I use:

SELECT id, expirationDate FROM `first-domain.com_ips` WHERE isBlocked = 1
UNION
SELECT id, expirationDate FROM `secons-domain.com_ips` WHERE isBlocked = 1
...;

I have an array which consists of domain names. So I'm looking for a way to use this domain array in SQL query. Maybe something like we use with SELECT. Example:

const ids = [3, 4, 6, 8];
const query = 'SELECT * FROM table WHERE id IN (' + ids.join() + ')';

Is there a way to use array for tables names in SQL? Thank you in advance!

3
  • 3
    Fix your data structure! Don't store a separate table for each domain. Include the domain as a column in a single table. Commented Dec 30, 2018 at 14:20
  • If there is any chance that the values from the ids array could come from the outside, unsterilized, then you'll want to use a prepared statement to build your query. Commented Dec 30, 2018 at 14:22
  • Please take a look at my posted answer, mark it as accepted answer if it solves your problem. Commented Dec 30, 2018 at 15:08

1 Answer 1

2

You can do this by using dynamic queries and regexps:

This dynamic query does what you want :

SELECT
  GROUP_CONCAT(
    CONCAT(
      'SELECT * FROM `',
      TABLE_NAME,
      '`') SEPARATOR ' UNION ALL ')
FROM
  `INFORMATION_SCHEMA`.`TABLES` 
WHERE
  `TABLE_NAME` REGEXP '_ips$'
INTO @sql;

SELECT @sql;

PREPARE stmt FROM @sql;
EXECUTE stmt;

This query gives two outputs, first is the final SQL query string which looks like :

SELECT * FROM `first-domain.com_ips` UNION ALL SELECT * FROM `second-domain.com_ips`

and the other output is the actual data from all tables, if you want only the final data, you can remove this statement:

SELECT @sql;
Sign up to request clarification or add additional context in comments.

3 Comments

Will try it in nearest time, when get to my computer. Thank you!
yes, it works! but could you explain where TABLE_NAME comes from? And what is INTO and @sql?
TABLE_NAME is a placeholder variable, that gets its value from INFORMATION_SCHEMA.TABLES , which holds all table names in your DB, so when you run this, it replaces it with the actual table name, putting a where clause defining regular expression "REGEXP '_ips$' that means, get all tables from table list that ends with '_ips'. The @sql is also variable that the select puts its result to, so it holds your final query string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.