我在3个(相同结构的)表中有3列产品:id,日期,请求。
当搜索特定的产品ID时,我想在所有表格中进行搜索(我不预先知道在哪个表格中可以找到产品ID)

table1非常大(超过1亿行),目前我正在使用此查询来创建一个临时表,用于对其执行其他查询。

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

SELECT ... FROM temp


由于table1的大小(超过1亿行),使用UNION合并3个表,然后查找id会花费很多时间,所以这不是正确的方法。

我想出的最快方法是(我将使用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.


但是,这样我最终会执行多个查询(如果id位于表3中,那么将执行4个查询)。

有没有更好的办法做到这一点与MySQL?

添加:

这样的事情会工作吗(什么是正确的语法,下面我会抛出错误)

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')
)

最佳答案

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

要么

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

07-25 22:48
查看更多