Skip to content

How can I query key's value in a text column from my table?  #4739

Closed

Description

@SuFIND

Hi,all.
There is a problem that has bothered me in recent days. I designed an org_score table using the MySql 5.7 database. In the table I designed "range" column of text type, using json string to store time.
The contents of this field are as follows:

{“timeStart”:"2017-01-01","timeEnd":"2017-02-01"}

I can use the sql of SELECT * FROM org_score WHERE range->'$.timeStart' >= '2017-01-01';

This way I can directly query the timeStart key under range. But I don't know how to use the ORM, statement of flask-sqlalchemy. Go check this result.

Activity

  1. added
    datatypes
    question
    on Jun 25, 2019
  2. zzzeek commented on Jun 25, 2019

    @zzzeek
    Member

    MySQL uses a function JSON_EXTRACT to extract elements from a JSON structure, SQLAlchemy renders this when you use the brackets operator:

    https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.JSON

    >>> from sqlalchemy import column, select, JSON
    >>> from sqlalchemy.dialects import mysql
    >>> stmt = select([column('q')]).where(column('range', JSON)['timeStart'] >= '2017-07-01')
    >>> print(stmt.compile(dialect=mysql.dialect())
    ... )
    SELECT q 
    WHERE JSON_EXTRACT(`range`, %s) >= %s
    
    
  3. zzzeek commented on Jun 25, 2019

    @zzzeek
    Member

    with literal binds:

    >>> print(stmt.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True}))
    SELECT q 
    WHERE JSON_EXTRACT(`range`, '$."timeStart"') >= '2017-07-01'
    
    

    the "->" thing is a synonym for json_extract

  4. zzzeek commented on Jun 28, 2019

    @zzzeek
    Member

    no activity here, closing

  5. SuFIND commented on Aug 26, 2019

    @SuFIND
    Author

    Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    datatypesmysqlquestion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions