📜  mariadb json 选择 - SQL (1)

📅  最后修改于: 2023-12-03 15:32:49.141000             🧑  作者: Mango

Mariadb JSON select - SQL

Mariadb is a popular database management system that supports JSON data type. With this, developers can store and retrieve JSON data in their database just like they would with any other data type. In this article, we will explore how to use Mariadb JSON select statements to query JSON data in your database.

Basic JSON Select Statement

A basic Mariadb JSON select statement looks like this:

SELECT jdoc->'$.key' FROM mytable WHERE jdoc->'$.key' = 'value';

In this statement, we are using the "->" operator to filter the JSON data in our table. The "->" operator is used to extract a JSON object or array element from a JSON string.

We are selecting the "key" value from the JSON data in our table where the "key" value equals "value". This will return all of the JSON objects in our table where this condition is true.

Filtering JSON Arrays

In Mariadb, we can query JSON arrays using the JSON_EXTRACT function. This function allows us to extract specific elements from a JSON array.

For example, if we have the following JSON data in our table:

{
  "names": ["John", "Mary", "Joe"]
}

We can extract the "Mary" element from the "names" array with the following select statement:

SELECT JSON_EXTRACT(jdoc, '$.names[1]') FROM mytable;

This will return the value "Mary" from our JSON data.

Filtering JSON Objects

To filter JSON objects, we can use the "->>" operator. This operator extracts a JSON object as a string.

For example, if we have the following JSON object in our table:

{
  "person": {
    "name": "John",
    "age": 30,
    "country": "United States"
  }
}

We can extract the "country" value using the "->>" operator:

SELECT jdoc->>'$.person.country' FROM mytable;

This will return the value "United States" from our JSON object.

Conclusion

Mariadb JSON select statements allow us to query JSON data stored in our database. With the right JSON operators and functions, we can filter and extract specific elements from our JSON data. This makes it easier for developers to work with JSON data in their Mariadb databases.