简体   繁体   English

SQL 选择列进行比较

[英]SQL Select columns with comparison

I have a SQL table which have a column named keywords .我有一个 SQL 表,其中有一列名为keywords

Table:桌子:

| id | keywords |

| 0 | music programming guitar |

Now i have an array like $array = array("boat", "water", "music");现在我有一个数组,如$array = array("boat", "water", "music"); . .

My target is to select all columns which have at least one of the things from the array in the keywords .我的目标是从keywords数组中选择至少具有其中一项内容的所有列。

Sql-Query: Sql查询:

"SELECT * FROM table WHERE keywords IN ('".$array."')";

It returns nothing.它什么都不返回。

The approach I am going to describe is highly not recommended.强烈不推荐我将要描述的方法。 The correct approach is to have a separate table with one row per id and keyword .正确的方法是有一个单独的表,每个idkeyword一行。 This is a junction table, and it would have rows like:这是一个联结表,它会有如下行:

id       keyword
1        music
1        programming
1        guitar

This is the right way to store lists in a relational database.这是在关系数据库中存储列表的正确方法。 Databases have this great data structure for lists.数据库具有用于列表的这种出色的数据结构。 It is called a table, not a string.它被称为表,而不是字符串。

But, if you are really stuck with this situation, then you can hack your way to a solution.但是,如果您真的遇到这种情况,那么您可以通过自己的方式找到解决方案。 Presumably, performance is not an issue.据推测,性能不是问题。

The hack is to format your list as a regular expression, and create the where clause as:黑客是将您的列表格式化为正则表达式,并将where子句创建为:

where keywords regexp 'boat|water|music'

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

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