[英]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? 例如,我想从站点3,7和15获取名称和电子邮件值。如何使用SQL查询执行此操作?
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:
为什么不能将“siteID”字段放入单个表中,这会将查询减少到:
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.
听起来你正试图在数据库引擎的TOP上实现自己的数据库,这已经非常适合进行这种关系数据处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.