简体   繁体   English

如何在多个查询中将查询结果存储给我们?

[英]How to store results from a query to us IN multiple queries?

Using PHP and Sqlite3, I have a query such as: 使用PHP和Sqlite3,我有一个查询,例如:

$firstquery = "SELECT id FROM mytable WHERE critera=........";

This can give me anywhere from 1 to many 1000's of id 's depending on the criteria. 根据标准,这可以给我从1到1000的id的任何地方。

I then use this found set in up to 40 other SQL queries on my page. 然后,我在页面上的多达40个其他SQL查询中使用了此发现集。 All are variations such as: 所有都是变体,例如:

$secondquery = "SELECT name FROM nametable WHERE nametable.id IN (".$firstquery.")";
$thirdquery = "SELECT car FROM cartable WHERE cartable.id IN (".$firstquery.")";

Now, when I have lots and lost of these $second, $third...$thirtiethquery the page starts getting slow and I think that constantly needing to run $firstquery over and over is not helping. 现在,当我有很多东西丢失了这些$ second,$ third ... $ thirtiethquery时,页面开始变慢,我认为不断需要反复运行$ firstquery并没有帮助。

Is there a way to avoid needing to run $firstquery over and over again? 有没有一种方法可以避免一遍又一遍地运行$ firstquery? Maybe storing the result as some way? 也许以某种方式存储结果? (I tried storing the result as a string and had it in the WHERE, but if there are thousands of id 's then the clause has too many parameters). (我尝试将结果存储为字符串,并将其存储在WHERE中,但是如果有数千个id ,则子句的参数太多。)

Thanks for any thoughts! 感谢您的任何想法! MacKniven MacKniven

If the first query is so slow that it noticeably affects your page load time, you should optimize it. 如果第一个查询非常慢,以至于明显影响您的页面加载时间,则应对其进行优化。

If it is still too slow, you have to temporarily store the result somewhere. 如果仍然太慢,则必须将结果临时存储在某个地方。

If there can be too many results, you can simply use a temporary table (a temporary table is not visible in other connections): 如果结果太多,则可以简单地使用一个临时表(该临时表在其他连接中不可见):

CREATE TEMPORARY TABLE FirstQueryResults AS
SELECT id FROM mytable WHERE critera=........;

SELECT name FROM nametable WHERE nametable.id IN FirstQueryResults;
...

DROP TABLE FirstQueryResults;

And if there can be many results, it might be worth it to create an index on the temporary table. 而且,如果可以有许多结果,那么值得在临时表上创建索引

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

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