mysql根据逗号分割的字符串去关联查询另外一个表的数据

1、说明

在做显示数据的时候,一个字段会存那种逗号分割的字符串,那如何去根据逗号分割字符串去查询另一个表的数据呢?

首先我们查看一下需要显示的数据

select * from company where f_id in ('210','205','208')

select * from company where f_id in ('210,205,208')

现在我要根据另一张模板表中的一个字段查询他下面的公司,存的是字符串类型

这时

select * from company where f_id in (select company_id from templet where f_id=583)

只查询出一条数据,说明他查询的结果是一个字符串'210,205,208',而我们需要的是'210','205','208',

这时会想到分割,但是发现需要循环很麻烦。这里提供正则表达式的方式解决如下

先把字符串替换成正则需要的样式,把‘210,205,208’转成210|205|208,再用正则匹配

SELECT
    GROUP_CONCAT(f_tran_type_name)
FROM
    company
WHERE
f_id REGEXP (
SELECT
   REPLACE (
  (
   SELECT
       company_id
FROM
    templet
   WHERE
       f_id = 583
   ),
     ',',
   '|'
)
)

2、优化

我们可以根据自己的需要写一个函数

def replace_sql(table, value, conditions):
    '''
    根据逗号分割的字符串去关联查询另外一个表的数据
    @table,表名-list[table1(存字典表), table2(存分割的字符串的表)]
    @value,返回的字段-list[table1_str, table2_str, table1_where_str]
    @conditions, 条件-dict
    '''
    sql = """SELECT GROUP_CONCAT({table1_str}) `names` FROM {table1} WHERE
                {table1_where_str} REGEXP (SELECT REPLACE ((SELECT {table2_str} FROM
                {table2} WHERE {con} ),',','|'));
        """
    con = dict_2_str(conditions)
    res_sql = sql.format(table1=table[0], table2=table[1],
                         table1_str=value[0], table2_str=value[1], table1_where_str=value[2],
                         con=con)
    return res_sql


def dict_2_str(dictin):
'''
将字典变成,key='value',key='value' 的形式
'''
tmplist = []
for k, v in dictin.items():
tmp = "%s='%s'" % (str(k), str(v))
tmplist.append(' ' + tmp + ' ')
return ','.join(tmplist)

 

如看详细https://www.cnblogs.com/edison20161121/p/7839950.html

原文地址:https://www.cnblogs.com/yuanfang0903/p/12704041.html