如何在mysql

时间:2017-07-29 15:22:23

标签: mysql json

假设我们有下表“文章”:

id_article | article_title
     1     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"}
     2     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"}
     3     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"}
     4     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"}
     5     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"}
     6     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"}
     7     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"}

让我们说我们还有以下表格'看见':

id_seen | id_item_seen
   1    |      3
   2    |      5
   3    |      5
   4    |      3
   5    |      3
   6    |      3
   7    |      3
   8    |      2
   9    |      2
   10   |      4
   11   |      1
   12   |      7
   13   |      7

我执行了以下SQL查询:

select articles.id_article, articles.id_article, count(*) as seens from seen
inner join articles on articles.id_article = seen.id_item_seen
group by articles.id_article
order by seens desc

这将返回以下结果:

id_article | article_title                                                     | seens
     1     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"} |   1
     2     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"} |   2
     3     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"} |   5
     4     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"} |   1
     5     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"} |   2
     6     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"} |   0
     7     | {"ar":"Arabic value", "en":"English value", "tr":"Turkish value"} |   2

这没关系,但我想要的不是所有存储的JSON {},而只是返回所需键的指定值(例如:“ar”),如下所示:

     1     | Arabic value |   1
     2     | Arabic value |   2
     3     | Arabic value |   5
     4     | Arabic value |   1
     5     | Arabic value |   2
     6     | Arabic value |   0
     7     | Arabic value |   2

我知道我们可以使用json_decode()函数使用PHP来完成这项工作,但是我们怎么能用SQL查询实现这个呢?

2 个答案:

答案 0 :(得分:1)

如果您使用的是MySQL 5.7并且该列是JSON类型(应该是这样),您可以使用

来检索它
select articles.id_article, articles.article_title->'$.ar', count(*) as seens from seen
inner join articles on articles.id_article = seen.id_item_seen
group by articles.id_article
order by seens desc

请参阅documentation of the JSON type

如果你有一个旧版本的MySQL,那么最好在服务器外部处理提取,以确保它得到妥善处理。

答案 1 :(得分:1)

在mysql中使用SBTRING_INDEX< 5.7.用你的列名替换json。

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('{"ar":"Arabic value", "en":"English value", "tr":"Turkish value"}','ar":"',-1),'"',1)

See it working.