【问题标题】:Postgres check if value exists in a table's columnPostgres 检查值是否存在于表的列中
【发布时间】:2021-11-04 15:20:03
【问题描述】:

我将如何检查一个名为 Table1 的表的 sess 列中是否存在名为 Dan 的值,该表包含 3 个名为 id、sess 和 timeD 的列。

会话类型为 JSON

Table1

id    sess                                         timeD
1     {"cookie":{expires:null}, "name": "Joey"}    12:30
2     {"cookie":{expires:null}, "name": "Dan"}      1:00
3     {"cookie":{expires:null}, "name": "Bob"}      1:20

【问题讨论】:

  • @bca 我正在检查 name 在 sess 列中是否具有值 Dan。我不检查该列是否为空
  • @jarlh 我正在阅读它,但是您如何确定这个名字是 Bob?
  • “sess”的列类型是什么?
  • 一般需要提供相关的schema(列和类型)、索引、postgres版本等

标签: javascript sql node.js database postgresql


【解决方案1】:

您可以使用包含运算符:@>

where sess @> '{"name": "Dan"}'

这假定sess 被定义为jsonb 列(它应该是)。如果不是,则需要投:sess::jsonb @> ...

【讨论】:

    【解决方案2】:

    这取决于sess 的列类型。 如果是字符串,您可以使用字符串匹配,例如

    where sess like '%"name": "Dan"%'
    

    如果是json,可以使用JSON functions and operators查询json对象内的值,例如

    where sess->>'name' = 'Bob'
    

    或者,如果它是字符串类型但包含 JSON,您可以将字符串解析为 JSON,然后在 JSON 上查询:

    where sess::json->>'name' = 'Bob'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2012-06-29
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      相关资源
      最近更新 更多