简体   繁体   English

Sql中的子查询

[英]Sub Queries in Sql

I'm using postgres as a database in my application.我在我的应用程序中使用 postgres 作为数据库。

In that I have a jsonb column and for storing json data inside it.因为我有一个 jsonb 列并用于在其中存储 json 数据。

{
    "id": "manohar",
    "array": [
        {
            "status": "active",
            "date": "13/12/2022"
        },
        {
            "status": "InActive",
            "date": "13/12/2021"
        }
    ]
}

so here every time I'm writing subqueries to select any field based on maximum date inside an array object.因此,每次我编写子查询以根据数组对象内的最大日期选择任何字段时,都会在这里。 Problem here is I have 100's of fields in each json object so every time I have to write subqueries for each feild.这里的问题是我在每个 json 对象中有 100 个字段,所以每次我必须为每个字段编写子查询时。

and after using subqueries looks less in performance.使用子查询后,性能看起来会降低。

Here is the Query that I'm using这是我正在使用的查询

Select 

(select t.sub_array->>'status'
from tbl_name d
  cross join lateral (
     select t.item  as sub_array
     from jsonb_array_elements(d.column_name -> 'array') as t(item)
      where t.item ->> 'date' <= TO_CHAR(CURRENT_DATE, 'YYYY-MM-DD')
     order by (t.item ->> 'date')::date desc
     limit 1
 ) t where t.primaryKey = d.key) as status

--like I have to write 100 subqueries for 100's fields 

from tbl_name t
where t.id='3'

I don't want to use Views for this requirements.我不想将视图用于此要求。

Any better approach or suggestions will be helpful..任何更好的方法或建议都会有所帮助。

Thanks..谢谢..

You must use the lateral view to access a JSON.您必须使用lateral view来访问 JSON。 But storing and accessing a JSON in a DB is not part of the best practices in SQL.但是在数据库中存储和访问 JSON 并不是 SQL 最佳实践的一部分。

In your case, I can only advise you to change your data model.在您的情况下,我只能建议您更改数据模型。 Storing JSON is one thing, you can use blob string to store it, that should be ok.存储JSON是一回事,你可以使用blob字符串来存储它,应该没问题。 But at the same time you write it, you should also explode its content in tables/columns/lines.但是在写的同时,还应该把它的内容分表/列/行。 Therefore, you can then access its content more easily.因此,您可以更轻松地访问其内容。

The idea is :这个想法是:

  • either you take time to write it properly (make a nice data architecture)要么你花时间正确地编写它(制作一个漂亮的数据架构)
  • or you take time to read it properly (make complexe SQL queries)或者您花时间正确阅读它(进行复杂的 SQL 查询)

This is just an example of what you should do.这只是您应该做什么的一个示例。 You probably need to find pretty names to reflect the business value of each of your objects.您可能需要找到漂亮的名称来反映每个对象的业务价值。

table "id"表“id”

ID ID NAME名称
1 1 manohar马诺哈尔

table "id_status"表“id_status”

id ID status地位 date日期
1 1 InActive不活跃 13/12/2021 13/12/2021
1 1 Active积极的 13/12/2022 13/12/2022

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

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