I am trying to extract a value from a string in a table like this below,
我试图从表中的字符串中提取一个值,如下所示,
query table,
query_id value
1 type={"page":"page"}&parent_id=10&image=on&content=on
2 type={"page":"page"}&parent_id=self
3 type={"category":"contact"}
as you can see the parent_id is in the query and sometimes is not.
正如您所看到的,parent_id在查询中,有时则不是。
I want to extract parent_id so I get this result,
我想提取parent_id所以我得到了这个结果,
query_id page_id value
1 10 type={"page":"page"}&parent_id=10&image=on&content=on
2 self type={"page":"page"}&parent_id=self
3 null type={"category":"contact"}
I try with this query,
我尝试这个查询,
SELECT
*,
CAST(
SUBSTRING(
value,PATINDEX('%parent_id=%', value) + 8,(PATINDEX('%&%', substring(value,PATINDEX('%parent_id=%', value),50)) - 9)
) AS INT
) AS page_id
FROM query
however I get this error,
但我得到这个错误,
1064 - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use
near 'INT ) AS page_id FROM query LIMIT 0, 30' at line 6
EDIT:
Maybe I should not be using PATINDEX
as I tested it with the query below,
也许我不应该使用PATINDEX,因为我使用下面的查询测试它,
SELECT
*,
SUBSTRING(
value,PATINDEX('%parent_id=%', value) + 8,(PATINDEX('%&%', substring(value,PATINDEX('%parent_id=%', value),50)) - 9)
) AS test
FROM query
I get this error,
我收到这个错误,
#1305 - FUNCTION mydb.PATINDEX does not exist
EDIT:
Got my answer,
得到了我的答案,
SELECT
*,
IF(LOCATE('parent_id=', value)>0,SUBSTRING_INDEX(SUBSTRING(value,LOCATE('parent_id=', value) + 10),'&',1),null)AS page_id
FROM query
1 个解决方案
#1
3
INT is already used in MYSQL. Use the right syntax
INT已经在MYSQL中使用。使用正确的语法
SELECT
*,
CAST(
SUBSTRING(
`value`,PATINDEX('%parent_id=%', `value`) + 8,(PATINDEX('%&%', substring(`value`,PATINDEX('%parent_id=%', `value`),50)) - 9)
) AS `INT`
) AS `page_id`
FROM `query`
#1
3
INT is already used in MYSQL. Use the right syntax
INT已经在MYSQL中使用。使用正确的语法
SELECT
*,
CAST(
SUBSTRING(
`value`,PATINDEX('%parent_id=%', `value`) + 8,(PATINDEX('%&%', substring(`value`,PATINDEX('%parent_id=%', `value`),50)) - 9)
) AS `INT`
) AS `page_id`
FROM `query`