【问题标题】:JSON VIEW using GROUP_CONCAT questionJSON VIEW 使用 GROUP_CONCAT 问题
【发布时间】:2011-01-09 08:26:13
【问题描述】:

嘿,DBA 和总体上很聪明的家伙。我有一个问题要问你。

我们使用 MySQL VIEW 将我们的数据在返回时格式化为 JSON(作为 BLOB),这很方便(虽然在性能上不是特别好,但我们已经知道这一点)。

但是,我现在似乎无法让特定的查询正常工作(每行包含 NULL,而它应该包含一个创建的 JSON 对象,该对象具有多个 JOIN 的值)。

大致思路如下:

SELECT CONCAT(
  "{",
     "\"some_list\":[", GROUP_CONCAT( DISTINCT t1.id ), "],",
     "\"other_list\":[", GROUP_CONCAT( DISTINCT t2.id ), "],",
  "}"
) cool_json

FROM table_name tn

INNER JOIN ( some_table st ) ON st.some_id = tn.id

LEFT JOIN ( another_table at, another_one ao, used_multiple_times t1  )
 ON st.id = at.some_id AND
    at.different_id = ao.different_id AND
    ao.different_id = t1.id

LEFT JOIN ( another_table2 at2, another_one2 ao2, used_multiple_times t2  )
 ON st.id = at2.some_id AND
    at2.different_id = ao2.different_id AND
    ao2.different_id = t2.id

GROUP BY tn.id ORDER BY tn.name

有人知道这里的问题吗?我错过了我应该分组的东西吗?当我只做 1 个 LEFT JOIN 和 GROUP_CONCAT 时它可以工作,但现在有多个 JOIN / GROUP_CONCAT 就搞砸了。

当我从“cool_json”字段中移动 GROUP_CONCAT 时,它们会按预期工作,但我希望我的数据格式为 JSON,以便我可以一步在服务器端或客户端对其进行解码。

【问题讨论】:

  • 您是否尝试过将此查询直接运行到数据库中。您在输出中是否收到有关 group_concat 的任何警告? group_concat 可以轻松达到 1024 个字符的自然限制。 (可以增加)
  • 我已经set global group_concat_max_len = 8192;(这已经足够了),但即使发生这种情况,它也只是切断了文本(我只收到NULL)。不错的猜测,不过,这是之前的问题(弄乱了我的 JSON)

标签: sql mysql json group-by


【解决方案1】:

我已经对此进行了一些测试,但找不到任何故障。

尝试创建一个类似的视图

CREATE VIEW tn_view AS
SELECT  tn.id, tn.name, t1.id, t2.id

FROM table_name tn

INNER JOIN ( some_table st ) ON st.some_id = tn.id

LEFT JOIN ( another_table at, another_one ao, used_multiple_times t1  )
 ON st.id = at.some_id AND
    at.different_id = ao.different_id AND
    ao.different_id = t1.id

LEFT JOIN ( another_table2 at2, another_one2 ao2, used_multiple_times t2  )
 ON st.id = at2.some_id AND
    at2.different_id = ao2.different_id AND
    ao2.different_id = t2.id

那么

SELECT CONCAT(
  "{",
     "\"some_list\":[", GROUP_CONCAT( DISTINCT t1.id ), "],",
     "\"other_list\":[", GROUP_CONCAT( DISTINCT t2.id ), "],",
  "}"
) cool_json
FROM tn_view
GROUP BY id ORDER BY name

【讨论】:

  • 是的,创建一个 VIEW 然后抓取该数据会起作用,但我想全部内联(我们周围已经有太多 VIEWS 了)。
猜你喜欢
  • 1970-01-01
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 2015-09-14
  • 2021-01-30
相关资源
最近更新 更多