如何在循环中运行SQL查询

时间:2021-01-08 00:56:36

How can I run this SQL query multiple times in a loop, where I replace the word 'pubs' with another word during each iteration. Is there a way to store an array of strings and loop through them?

如何在循环中多次运行这个SQL查询,在每次迭代中,我都用另一个单词替换单词“pub”。是否有一种方法来存储字符串数组并对它们进行循环?

SELECT * FROM businesses WHERE category='pubs'

2 个解决方案

#1


3  

In general, it's usually better performance-wise to do bulk or batch queries than queries in a loop, since you can save round trip calls to the DB.

一般来说,与循环中的查询相比,执行批量查询或批处理查询通常更好,因为可以保存对DB的往返调用。

Consider instead doing something like SELECT * from businesses WHERE category IN ('pubs', ...), or if you plan to iterate over all categories, retrieve all item rows and programmatically use category in the returned models to do what you need to with them.

相反,可以考虑从类别中(“pub”,…)的业务中选择*,或者如果您计划遍历所有类别,检索所有项行,并在返回的模型中以编程方式使用category来处理它们。

If you absolutely must use a loop, you can look at the loop documentation.

如果一定要使用循环,可以查看循环文档。

#2


1  

You probably don't need a loop to run them rather use a IN clause to include all the possible condition values like

您可能不需要循环来运行它们,而是使用IN子句来包含所有可能的条件值,比如

SELECT * FROM businesses WHERE category IN ('pubs','subs','nubs')

#1


3  

In general, it's usually better performance-wise to do bulk or batch queries than queries in a loop, since you can save round trip calls to the DB.

一般来说,与循环中的查询相比,执行批量查询或批处理查询通常更好,因为可以保存对DB的往返调用。

Consider instead doing something like SELECT * from businesses WHERE category IN ('pubs', ...), or if you plan to iterate over all categories, retrieve all item rows and programmatically use category in the returned models to do what you need to with them.

相反,可以考虑从类别中(“pub”,…)的业务中选择*,或者如果您计划遍历所有类别,检索所有项行,并在返回的模型中以编程方式使用category来处理它们。

If you absolutely must use a loop, you can look at the loop documentation.

如果一定要使用循环,可以查看循环文档。

#2


1  

You probably don't need a loop to run them rather use a IN clause to include all the possible condition values like

您可能不需要循环来运行它们,而是使用IN子句来包含所有可能的条件值,比如

SELECT * FROM businesses WHERE category IN ('pubs','subs','nubs')