搜索多个tables.column以获取特定值

时间:2011-12-03 00:30:38

标签: mysql

我有多个表(8)具有相同的列名。每个表都是一个站点。我希望能够搜索哪个table.column具有特定值。即。 table.subnet = '10 .3.30.x'。提前谢谢。

2 个答案:

答案 0 :(得分:1)

查看UNION ALL关键字。我想你想做的是这样的事情:

(SELECT 'table1', table1.* FROM table1 where subnet = '10.3.30.x')
UNION ALL
(SELECT 'table2', table2.* FROM table2 where subnet = '10.3.30.x')
UNION ALL
...
(SELECT 'table7', table7.* FROM table7 where subnet = '10.3.30.x')
UNION ALL
(SELECT 'table8', table8.* FROM table8 where subnet = '10.3.30.x')

这样,您的结果将包含子网值为指定值的所有列,以及该行所在表的名称。

答案 1 :(得分:1)

您可以使用UNION获取单个查询中的所有值:

SELECT 'table1', subnet FROM table1 WHERE subnet = '10.3.30.x'
UNION
SELECT 'table2', subnet FROM table2 WHERE subnet = '10.3.30.x'
UNION
SELECT 'table3', subnet FROM table3 WHERE subnet = '10.3.30.x'
UNION
SELECT 'table4', subnet FROM table4 WHERE subnet = '10.3.30.x';