gpt4 book ai didi

php - MySQL在(结构相同)多个表中搜索id

转载 作者:行者123 更新时间:2023-11-29 19:29:53 26 4
gpt4 key购买 nike

我的产品位于 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';

从 information_schema.columns 中选择表名、列名,其中列名 = '列名';

关于php - MySQL在(结构相同)多个表中搜索id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com