我正在处理一个 MySQL 数据库,其中有数量不确定的相同结构的表,如下所示:
foo_reference1
foo_reference2
foo_referencea
foo_referenceb
....
foo_referencez
Run Code Online (Sandbox Code Playgroud)
该表中的所有包含的字段foo_id
,bar_id
以及bar_weight
。我需要获取bar_id
按bar_weight
(降序)排序的前五个字段,其中foo_id
等于每个表中的某个值。
问题是,没有两台服务器会拥有完全相同数量的表或相同的名称。但是,它们总是以foo_reference
. 我需要在几十个地方运行它。在理想的世界中,只会有一个正确索引的foo_reference
表,不幸的是,更改是不可能的。
最初,我尝试仅SHOW TABLES LIKE 'foo_reference%'
在子查询中使用以构建必须查询的表列表。显然,MySQL不喜欢这样,所以我直接查询了信息模式:
select bar_id, bar_weight from
(
select table_name as name
from information_schema.tables as tmp
where tmp.table_name like 'foo_reference%'
) as res
where res.foo_id = '1'
order by res.bar_weight desc
limit 0, 5;
Run Code Online (Sandbox Code Playgroud)
MySQL 告诉我这bar_id
是字段列表中的未知列。当我自己运行子查询时,它返回需要查询的表列表。
我做错了什么?我想要的是bar_id
每个表中的前 5 个字段,其中foo_id
是某个数字。正如您所看到的,当我来到这里时,我正在做一些学习(以及很多猜测)。