简体   繁体   English

MySQL在(相同结构的)多个表中搜索ID

[英]MySQL search for id in (identically structured) multiple tables

I have products in 3 (identically structured) tables with 3 columns columns: id, date, requests. 我在3个(相同结构的)表中有3列的产品:ID,日期,请求。 When searching for a specific product id I'd like to search in all tables (I don't know in advance in which table the product id can be found) 当搜索特定的产品ID时,我想在所有表格中进行搜索(我不知道可以在哪个表格中找到产品ID)

table1 is very large (over 100 million rows), and currently I'm using this query to create a temporary table which I use to perform other queries on. table1非常大(超过1亿行),目前我正在使用此查询来创建一个临时表,并使用该表执行其他查询。

CREATE TEMPORARY TABLE temp ENGINE=MEMORY 
as (select DISTINCT id, date, requests from table1 WHERE id='$id');

SELECT ... FROM temp

Merging the 3 tables using UNION and then look for the id takes forever due to the size of table1 (over 100 million rows), so that is not the right approach. 由于table1的大小(超过1亿行),使用UNION合并3个表,然后查找id会花费很多时间,所以这不是正确的方法。

The fastest way I came up with is (I would do this using PHP): 我想出的最快方法是(我将使用PHP进行此操作):

search table1, if id found create temporary table, 
if id not found in table 1 then
search table2, if id found create temporary table, 
if id not found in table 2 then
search table3, if id found create temporary table, 
if id not found in table3 then return id not found. 

However this way I end up performing multiple queries (if id is located in table 3 then 4 queries will have been executed). 但是,这样我最终会执行多个查询(如果id位于表3中,那么将执行4个查询)。

is there a better way of doing this with MySQL? 有没有更好的办法做到这一点与MySQL?

ADDED: 添加:

Would something like this work (what is the proper syntax for this, what I have below throws an error) 这样的事情会工作吗(什么是正确的语法,下面我会抛出错误)

CREATE TEMPORARY TABLE temp ENGINE=MEMORY 
as (
(select DISTINCT id, date, requests from table1 WHERE id='$id')
UNION
(select DISTINCT id, date, requests from table2 WHERE id='$id')
UNION
(select DISTINCT id, date, requests from table3 WHERE id='$id')
)

try this 尝试这个
SELECT * FROM information_schema.columns WHERE column_name = 'column_name';

or 要么

SELECT table_name, column_name FROM information_schema.columns WHERE column_name = 'column_name';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM