How to get values from MySQL(5.6) column if that contains json document as string

前端 未结 10 696
萌比男神i
萌比男神i 2020-12-02 18:48

How to get values from MySQL(5.6) column if that contains JSON document as a string

For example, if we have a table - employee in that we have three columns id, nam

10条回答
  •  天命终不由人
    2020-12-02 19:45

    Both previous answers didn't work for me when the element wasn't mentioned in JSON text. There is my improved function:

    DELIMITER $$
    
    DROP FUNCTION IF EXISTS `json_extract_c`$$
    
    CREATE FUNCTION `json_extract_c`(
    details TEXT,
    required_field VARCHAR (255)
    ) RETURNS TEXT CHARSET latin1
    BEGIN
      DECLARE search_term TEXT;
      SET details = SUBSTRING_INDEX(details, "{", -1);
      SET details = SUBSTRING_INDEX(details, "}", 1);
      SET search_term = CONCAT('"', SUBSTRING_INDEX(required_field,'$.', - 1), '"');
      IF INSTR(details, search_term) > 0 THEN
        RETURN TRIM(
          BOTH '"' FROM SUBSTRING_INDEX(
            SUBSTRING_INDEX(
              SUBSTRING_INDEX(
                details,
                search_term,
                - 1
              ),
              ',"',
              1
            ),
            ':',
            -1
          )
        );
      ELSE
        RETURN NULL;
      END IF;
    END$$
    
    DELIMITER ;
    

提交回复
热议问题