多次 Table 搜索,使用 Limit 子句和已知结果源 Table 名称

Multiple Tables Search, with Limit Clause and Known Result Source Table Names

出现了一种情况,我必须从一个公共 ID 中试探性地找出一个 table 名称。 tables 具有完全相同的结构,所以我认为 unionunion all 将按照此处一些答案的建议工作。问题是,对查询应用 limit 子句 效果不佳。如果我将它应用于 多个 select 查询 ,它会失败;如果 在一个 上,它只过滤那个 table 作为主要。即使 包装它 如下所示也没有产生所需的结果 - 即:将每个单独查询的返回结果限制为一行.

重述问题:我如何知道已知 table 的列表是否具有特定值(命名列)?

一个开放的选项提供了很好的 table 来源作为别名,但禁止多重限制;结果可能很多:

SELECT `ID`, `BATCH_NUMBER`, 'TBL1' AS 'table_one' FROM `table_one` WHERE `NAMED_ID` = '123' 
UNION ALL
SELECT `ID`, `BATCH_NUMBER`, 'TBL2' AS 'table_two' FROM `table_two` WHERE `NAMED_ID` = '123' 
UNION ALL
SELECT `ID`, `BATCH_NUMBER`, 'TBL3' AS 'table_three' FROM `table_three` WHERE `NAMED_ID` = '123'

仅在找到前 table 个结果时包装选项过滤器;我们需要所有 table 的值。

select * from (
SELECT `ID`, `BATCH_NUMBER`, 'TBL1' AS 'table_one' FROM `table_one` WHERE `NAMED_ID` = '123' 
UNION ALL
SELECT `ID`, `BATCH_NUMBER`, 'TBL2' AS 'table_two' FROM `table_two` WHERE `NAMED_ID` = '123' 
UNION ALL
SELECT `ID`, `BATCH_NUMBER`, 'TBL3' AS 'table_three' FROM `table_three` WHERE `NAMED_ID` = '123' 
) as resutl_table  
LIMIT 1

如果您只想要 table 个名称,那么您的每个查询都应该 return 只在第一列:

SELECT 'TBL1' AS table_name FROM `table_one` WHERE `NAMED_ID` = '123' 
UNION
SELECT 'TBL2' AS table_name FROM `table_two` WHERE `NAMED_ID` = '123' 
UNION
SELECT 'TBL3' AS table_name FROM `table_three` WHERE `NAMED_ID` = '123'

或者,获取以逗号分隔的字符串形式的结果:

SELECT GROUP_CONCAT(table_name) AS table_names
FROM (
  SELECT 'TBL1' AS table_name FROM `table_one` WHERE `NAMED_ID` = '123' 
  UNION
  SELECT 'TBL2' AS table_name FROM `table_two` WHERE `NAMED_ID` = '123' 
  UNION
  SELECT 'TBL3' AS table_name FROM `table_three` WHERE `NAMED_ID` = '123'
) t

UNION 将过滤掉重复项。