繁体   English   中英

sqlite中MySQL中find_in_set(value,set)的等效函数是什么?

[英]What is the equivalent function in sqlite for find_in_set(value,set) in MySQL?

下面的示例是wrt MySQL。 例如:test1如下

+----+------------------------+
| id | name                   |
+----+------------------------+
|  2 | 1,2                    |
| 33 | 2,44,33,5              |
|  1 | 11,4,55                |
| 12 | 11,111,122,551,112,221 |
+----+------------------------+

test1选择*,其中find_in_set('122',name)

将执行以下操作:

+----+------------------------+
| id | name                   |
+----+------------------------+
| 12 | 11,111,122,551,112,221 |
+----+------------------------+

在Sql Lite中,像这样使用:

select * 
from `test1` 
where name like '%,122,%'
or name like '122,%'
or name like '%,122'
or name = '122'

一件事:

我的价值是551,122。 在这种情况下,由于值是从appln返回的,因此我们可以拆分value列并将查询写为

(',' || column_name || ',') LIKE '%,551,%' or
(',' || column_name || ',') LIKE '%,122,%'

有什么最好的主意来解决这个问题吗?

我想避免喜欢。 还有其他想法吗?

我的第一个想法是,不应将CSV数据存储在关系数据库中的列中,而应使用单独的关联表。

您可以使用LIKE来完成这项工作。 您的评论表明您看到了三种情况,但实际上有四种:

select *
from test1
where name like '122,%'
   or name like '%,122'
   or name like '%,122,%'
   or name    = '122'     /* You forgot about this degenerate case */

索引可以用于最后一种情况,也可以用于第一种情况,但中间的两种可能是表扫描。 如果您强制数据始终使用开头和结尾的逗号,则可以简化查询:

+----+--------------------------+
| id | name                     |
+----+--------------------------+
|  2 | ,1,2,                    |
| 33 | ,2,44,33,5,              |
|  1 | ,11,4,55,                |
| 12 | ,11,111,122,551,112,221, |
+----+--------------------------+

然后,您可以只使用一个LIKE(不使用索引):

select *
from test1
where name like '%,122,%'

但是,您实际上应该使用关联表,以便可以使用where name = 122并连接到其他表。

我更喜欢约翰·韦尔登(John Weldon)提到的策略,

所以,

select *
from test1
where (',' || column_name || ',') LIKE '%,122,%' //any value 

参考

创建一个功能

public class ConnectionOpenHandler extends Interceptor{
  private static final long serialVersionUID=1;
  private String nameConnection;
  private String jdbcUrl;

  public void handler(Handler handler) throws Exception{
    Context context=(Context)handler.getProperty("context");
    SessionContext sessionContext=(SessionContext)context;

    Class.forName("org.sqlite.JDBC");
    Connection connection=DriverManager.getConnection(jdbcUrl);
    connection.setAutoCommit(false);
    handler.setProperty(nameConnection,connection);
    sessionContext.getProtectedContext().setProperty(nameConnection,connection);

    Function.create(connection,"find_in_set",new FindInSet());
  }
  private class FindInSet extends Function{
    protected void xFunc() throws SQLException{
      String row=this.value_text(0);
      String values=this.value_text(1);

      if(values==null){
        result(0);
        return;
      }

      boolean ok=Arrays.asList(values.split("\\,")).contains(row);
      result(ok?1:0);
    }
  }
}

暂无
暂无

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

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