1

在 Debian 上使用 MySQL 5.1.66-0+squeeze1-log,我得到一个我不明白的 GROUP BY 结果。

如果我 GROUP BY data,则组合不相等data的值,这对我来说没有任何意义。如果我在同一列 SHA1( data) 上对哈希值进行 GROUP BY,则一切正常,并且仅将相同的值data组合到组中。

这里发生了什么?似乎 GROUP BY 只考虑列的前 x 个字符。如果不是这样,为什么还会发生这种情况?这可能只是我脑子里的一个转折吗?

data编辑 1: (json-encoded legacy - 当我更笨的时候;)的示例值:

{"a":[{"val":{"tcn":{"1980":"1","1981":"1","1982":"1","1983":"1","1984":"1","1985":"1","1986":"1","1987":"1","1988":"1","1989":"1","1990":"1","1991":"1","1992":"1","1993":"1","1994":"1","1995":"1","1996":"1","1997":"1","1998":"1","1999":"1","2000":"1","2001":"1","2002":"1","2003":"1","2004":"1","2005":"1","2006":"1","2007":"1","2008":"1","2009":"1","2010":"1"},"sic":{"1980":"1","1981":"1","1982":"1","1983":"1","1984":"1","1985":"1","1986":"1","1987":"1","1988":"1","1989":"1","1990":"1","1991":"1","1992":"1","1993":"1","1994":"1","1995":"1","1996":"1","1997":"1","1998":"1","1999":"1","2000":"1","2001":"1","2002":"1","2003":"1","2004":"1","2005":"1","2006":"1","2007":"1","2008":"1","2009":"1","2010":"1"}}}],"b":[{"val":{"tcn":{"1980":"1","1981":"1","1982":"1","1983":"1","1984":"1","1985":"1","1986":"1","1987":"1","1988":"1","1989":"1","1990":"1","1991":"1","1992":"1","1993":"1","1994":"1","1995":"1","1996":"1","1997":"1","1998":"1","1999":"1","2000":"1","2001":"1","2002":"1","2003":"1","2004":"1","2005":"1","2006":"1","2007":"1","2008":"1","2009":"1","2010":"1"},"sic":{"1980":"1","1981":"1","1982":"1","1983":"1","1984":"1","1985":"1","1986":"1","1987":"1","1988":"1","1989":"1","1990":"1","1991":"1","1992":"1","1993":"1","1994":"1","1995":"1","1996":"1","1997":"1","1998":"1","1999":"1","2000":"1","2001":"1","2002":"1","2003":"1","2004":"1","2005":"1","2006":"1","2007":"1","2008":"1","2009":"1","2010":"1"}}}],"0":[{"val":{"com":{"able":"2"}},"str":{"com":{"comm":"According","src":{"1":{"name":"law 256","articles":"B2\/2.11","links":"","type":""},"2":{"name":"law 298","articles":"B.19\/2.3","links":"","type":""}}}}}]}

编辑 2:很抱歉遗漏了代码,我认为它会使其更短更容易。显然情况正好相反……

SELECT
    GROUP_CONCAT(resid) AS ids
    ,data
FROM resdata
GROUP BY data

对比

SELECT
    GROUP_CONCAT(resid) AS ids
    ,CAST(SHA1(data) AS CHAR(40)) AS hash
    ,data
FROM resdata
GROUP BY hash
4

1 回答 1

1

我终于弄明白了。仅当存在 GROUP_CONCAT() 时才会出现问题,正如在按文本字段分组时的 GROUP_CONCAT() 行计数中所讨论的那样(我只是在弄清楚它链接到 concat :s 后才发现它)。

ORDER BY、DISTINCT 和(间接)GROUP_CONCAT() 都依赖于max_sort_length系统变量。任何使用这些运算符/函数的查询都只会考虑列的第一个 max_sort_length 字节,在我的例子中是默认的 1024 字节。

尽管 GROUP BY 不使用 ORDER BY,但 GROUP_CONCAT() 默认情况下对您在 GROUP BY 语句中使用的列使用 ORDER BY。(感谢Saharsh Shah1 月 4 日 12:42

data列中的大多数值都比 max_sort_length 长得多。在我的例子中,有 377 行的前 1024 个字节相同,但其余的不同。因此,在我的例子中,DISTINCT 和 GROUP BY 只会返回 2360 行,即使有 2737 个不同的值。

因此,对文本长度超过 max_sort_length 的文本列进行分组时要小心!它可能不代表在 INT 和较小的 CHAR 上操作时习惯的不同结果。DISTINCT 将显示相同的行为,在使用它检查 GROUP BY 的完整性时会给您一个误报。

于 2013-09-03T21:16:21.787 回答