简体   繁体   English

如何遍历SQL查询并在每次迭代期间更改一个参数

[英]How to loop through SQL queries and change one parameter during each iteration

How can I run this SQL query multiple times in a loop, where I replace the word 'awesome' with another word during each iteration. 如何在一个循环中多次运行此SQL查询,在每次循环中我用另一个单词替换“ awesome”一词。 Is there a way to store an array of strings and loop through them? 有没有办法存储一个字符串数组并遍历它们?

I am trying to find the reviews in my database that mention the word 'awesome' but I also want to run this query on several other words without having to run them one by one and manually replacing the word 'awesome' 我正在尝试在数据库中找到提及“ awesome”一词的评论,但我也想对其他几个词运行此查询,而不必一次一个地运行它们并手动替换“ awesome”一词

SELECT * FROM books WHERE review_text LIKE '%awesome%'
CREATE TABLE SearchStrings (SearchString VARCHAR(50));

INSERT INTO SearchStrings (SearchString)
VALUES ('string1'),('string2');

SELECT *
FROM
    books b
    INNER JOIN SearchStrings s
    ON b.review_text LIKE CONCAT(CONCAT('%',s.SearchString),'%')
;

In a single query you can just append all of the different search text you want to included in a list of ORs in the WHERE clause. 在单个查询中,您可以仅将要包括在WHERE子句中的OR列表中的所有不同搜索文本追加。

SELECT * 
FROM books 
WHERE review_text LIKE '%awesome%'
OR review_text LIKE '%blossum%'
OR review_text LIKE '%possum%'
OR review_text LIKE '%bean-soup%'

And you can just append as many as you need to search by. 您可以根据需要添加任意数量的内容。 This also has the added benefit of saving you round trips to the database, making this single query much faster than several independent queries. 这还有一个额外的好处,那就是节省了往返数据库的时间,从而使单个查询比几个独立查询快得多。

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

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