如何使用数组创建MySQL查询?(How do I create a MySQL query using an array?)

我需要一个数组并将其用于MySQL查询。

我尝试寻找方法,但所有这些方法似乎都与PHP数组有关,而不是Ruby。

例如,我有terms = ['genetics', 'elderly', 'health'] ,我想使用:

con.query "SELECT col1 FROM data1 WHERE MATCH (col2) AGAINST (terms)"

这可能吗?

I need to take an array and use it for a MySQL query.

I tried looking for methods but all of them seem to be related to PHP arrays and not Ruby.

For example, I have terms = ['genetics', 'elderly', 'health'] and I want to use:

con.query "SELECT col1 FROM data1 WHERE MATCH (col2) AGAINST (terms)"

Is this possible?

最满意答案

您可以在against条款中join您的条款:

terms = ['genetics' , 'elderly', 'health'] con.query "SELECT col1 FROM data1 WHERE MATCH col2 AGAINST ('#{terms.join(' ')}')"

请注意,使用match/against几乎肯定会比使用一系列like子句更具表现力。 有关更多信息,请参阅此StackOverflow答案: 哪个SQL查询更好,MATCH AGAINST还是LIKE? 。

查看MySQL文档以获取有关全文搜索的更多信息(包括可能的运算符): http : //dev.mysql.com/doc/refman/5.5/en/fulltext-search.html 。

You can just join your terms in your against clause:

terms = ['genetics' , 'elderly', 'health'] con.query "SELECT col1 FROM data1 WHERE MATCH col2 AGAINST ('#{terms.join(' ')}')"

Note that using match/against will almost certainly be more performative than using a series of like clauses. See this StackOverflow answer for more information: Which SQL query is better, MATCH AGAINST or LIKE?.

Check out the MySQL documentation for more information on full text searching (including possible operators): http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html.

更多推荐