mysql pgsql json array specified condition traversal query through select specified condition to perform traversal query matching in json array, without writing additional functions

mysql pgsql json array specified condition traversal query through select specified condition to perform traversal query matching in json array, without writing additional functions

Database server environment

database Version
mysql 5.7.34
PostgreSQL 10.3

Original table structure and data

create table students
    (
        name varchar,
        gender varchar,
        age int,
        scores jsonb
);

INSERT INTO public.students (name, gender, age, scores) VALUES ('张三', '男', 34, '[{"语文": "78"},{"数学": "90"}]');
INSERT INTO public.students (name, gender, age, scores) VALUES ('李四', '女', 21, '[{"语文": "89"},{"数学": "67"}]');
INSERT INTO public.students (name, gender, age, scores) VALUES ('王二', '女', 27, null);

select *
from students ;

students

name gender age scores
Zhang San male 34 [{"Chinese": "78"}, {"Mathematics": "90"}]
John Doe female 21 [{"Chinese": "89"}, {"Mathematics": "67"}]
Wang Er female 27 NULL

pgsql

SQL

select *, (scores -> 0 )->>'语文' ::text as score
from students
where scores is not null
  AND exists(
        select 1
        from jsonb_array_elements(students.scores) r
        where r->>'语文' > '80'
    );

result

name gender age scores score
John Doe female 21 [{"Chinese": "89"}, {"Mathematics": "67"}] 89

mysql(TODO。。。

SQL


result


Introduction to related articles

mysql uses temporary variables in the select query statement to accumulate sum;
among the records with the same column value, the largest or latest one is selected according to the conditions;
mysql calculates the distance and sorts by longitude and latitude

mysql pgsql realizes that multiple rows of records are merged into one row and grouped and merged with specified characters for splitting

mysql pgsql multi-line record to JSON array field row to json column

Guess you like

Origin blog.csdn.net/wangxudongx/article/details/128066571