【问题标题】:Search from comma separated values从逗号分隔值中搜索
【发布时间】:2018-01-22 06:04:18
【问题描述】:

我有包含city_id 列的用户表,并且在此列内,城市 ID 存储为逗号分隔值,如下所示:

用户

user_id  user_name     city_id    
1        ahmar_arshad   1,2,3
2        abdul_muiz     15,2,9
3        abdul_momin    1,2,13

现在我想从city_id 列中搜索包含城市id = 1 的行。

如何做到这一点?

【问题讨论】:

  • MySQLPostgreSQL?
  • 我需要在 PostgreSQL 中。
  • 考虑 3NF .....

标签: sql postgresql


【解决方案1】:

这是一个通用的解决方案,应该适用于 Postgres:

SELECT *
FROM yourTable
WHERE ',' || city_id || ',' LIKE '%,1,%';

Demo

这里的技巧是比较表单中城市 ID 的 CSV 列表,例如,1,2,3,,ID,,其中 ID 可以是任何单独的城市 ID。

请注意,最好对表格进行规范化,并将这些城市 ID 存储在单独的记录中,而不是存储在 CSV 字符串中。这将使查询数据更容易,并且可能还会提高性能。

【讨论】:

    【解决方案2】:

    检查一下。

    您应该使用string_to_array 来溢出列,然后在 where 子句中使用 city_id='1' 条件。

    select * from (
    select id,user_name,unnest(string_to_array(city_id, ',')) city_id
    from RT
    )a where city_id='1'
    

    在这里查看Demo

    输出

    【讨论】:

      【解决方案3】:

      如果将逗号分隔的列表转换为数组,则可以使用 Postgres 强大的数组运算符:

      select *
      from cities
      where '1' = any (string_to_array(city_id, ','));
      

      如果您需要查找具有多个 ID 的行

      select *
      from cities
      where string_to_array(city_id, ',') && array['1', '2']
      

      && 是数组的“重叠”运算符。如果您需要查找包含所有 ID 列表的行:您可以使用 contains 运算符:

      select *
      from cities
      where string_to_array(city_id, ',') @> array['1', '2']
      

      【讨论】:

        【解决方案4】:

        试试这个查询!

        SELECT      *
        FROM        [Table Name]
        WHERE       city_id  LIKE '1,%,%' 
        OR          city_id  LIKE '%,1,%'
        OR          city_id  LIKE '%,%,1';
        

        【讨论】:

        • 如果列只包含一个值,那么它会失败,所以没有逗号,或者只有 2 个值,或者 4 个或更多
        【解决方案5】:

        试试这个..

        --********************************************* *******************************************

        --为引用创建表结构

        创建表#test(user_id int,user_name varchar(100),city_id varchar(25))

        插入#test 值 (1,'ahmar_arshad','1,2,3') 插入#test值(1,'abdul_muiz','15,2,9') 插入#test值(1,'abdul_momin','1,2,13')

        --从#test中选择*

        --********************************************* *******************************************

        --查询

        从中选择 user_id、user_name、city_id ( 选择 user_id,user_name,city_id,replace(city_id,',','') 作为 City_ID2 来自#测试 )一种 其中 City_ID2 像 '%1%'

        -- 用星号(*)替换逗号,然后搜索。

        --********************************************* *******************************************

        【讨论】:

        • 更新查询.. select user_id,user_name,city_id from (select user_id,user_name,city_id,replace(city_id,',','*') as City_ID2 from #test )A where City_ID2 like ' %1*%'
        【解决方案6】:
        SELECT *
        FROM user
        WHERE  user_id LIKE '%1%';
        

        你可以在 w3school 上搜索 like 关键字

        【讨论】:

        • 这将匹配 ID 13,因为 % 匹配 1 后跟任何内容(不是我的反对票)。
        猜你喜欢
        • 1970-01-01
        • 2018-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多