简体   繁体   中英

MySQL - Select specific rows from multiple tables

I have a set of database tables named like:

site_1_details
site_2_details
site_3_details
...
site_420_details

all tables have the same fields, like:

ID  | SETTING | VALUE 
----------------------
1     name      Site 1 Name
2     desc      Site 1 Desc
3     email     Site 1 Email...
...

(only the value fields are different)

How can I get a set of values from certain tables?

For example, I want to get the name & email values from sites 3,7 and 15. How could I do that with a SQL query?

SELECT 3 AS siteID, name, email
FROM site_3_details

UNION

SELECT 7 AS siteID, name, email
FROM site_7_details

UNION

SELECT 15 AS siteID, name,email
FROM site_15_details

This is a horribly bad design. Why couldn't you put a "siteID" field into a single table, which'd reduce the query to:

SELECT name, email
FROM site_details
WHERE siteID IN (3,7,15);

comment followup:

Ah well, then you just modify the individual queries:

SELECT 7 AS siteID, ID as fieldID, name AS fieldName
FROM site_7_details WHERE SETTING IN ('name', 'email')

UNION

....

Any reason you've designed the tables like this? Sounds like you're trying to implement your own database on TOP of a database engine which is already perfectly suited to doing this kind of relational data handling.

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