MySQL LEFT JOIN ON JSON获取值

时间:2017-09-18 14:14:24

标签: mysql json

Streams:

+----+-----------+
| id |   server  |
+----+-----------+
|  1 | ["1","15"]|
+----+-----------+

Servers:

+----+-------------------+------------------+
| id | server            |      download    |
+----+-------------------+------------------+
|  1 | Server #1         |      2.05        |
|  2 | Server #2         |      23.96       |
|  3 | Server #3         |      8.08        |
| 15 | Server #15        |      3.03        |
+----+-------------------+------------------+

我需要得到结果:

+----+-----------+--------------+
| id |   server  |  download    |
+----+-----------+--------------+
|  1 | Server #1 |     2.05     |
+----+-----------+--------------+

所以基本上我需要从流表服务器字段获取并且该字段需要从服务器表中读取哪个服务器具有较低的下载并返回该服务器,如上面发布的reult表。

SELECT servers.server FROM servers
LEFT JOIN streams ON servers.id=CAST(json_extract(streams.server, '$[0]') AS 
UNSIGNED)
WHERE streams.id=1;

所以我从结果中得到的第一台服务器不是两个...所以我可以比较一下有爱人下载...我知道问题是'$ [0]'但我不知道如何离开加入或者如何从流服务器(1和15)读取所有值,然后添加女巫是这两个人的情人...我错过了什么?

1 个答案:

答案 0 :(得分:1)

我想你也应该像这样再次提取第二个JSON值和LEFT JOIN

SELECT servers.server FROM servers

LEFT JOIN streams ON servers.id = CAST(json_extract(streams.server, '$[0]') AS 
UNSIGNED)    
LEFT JOIN streams ON servers.id = CAST(json_extract(streams.server, '$[1]') AS 
UNSIGNED)

WHERE streams.id = 1;