使用 MySQL,我可以执行以下操作:
Using MySQL, I can do something like:
SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;
我的输出:
shopping
fishing
coding
但我只想要 1 行,1 列:
but instead I just want 1 row, 1 col:
预期输出:
shopping, fishing, coding
原因是我从多个表中选择多个值,在所有连接之后,我得到的行比我想要的多得多.
The reason is that I'm selecting multiple values from multiple tables, and after all the joins I've got a lot more rows than I'd like.
我在 上寻找了一个函数MySQL Doc 它看起来不像 CONCAT 或 CONCAT_WS 函数接受结果集.
I've looked for a function on MySQL Doc and it doesn't look like the CONCAT or CONCAT_WS functions accept result sets.
这里有人知道怎么做吗?
So does anyone here know how to do this?
您可以使用 GROUP_CONCAT:
You can use GROUP_CONCAT:
SELECT person_id,
GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
正如 Ludwig 在他的评论中所述, 您可以添加 DISTINCT 运算符以避免重复:
As Ludwig stated in his comment, you can add the DISTINCT operator to avoid duplicates:
SELECT person_id,
GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
正如 Jan 在他们的评论中所述, 您还可以在使用 ORDER BY 内爆之前对值进行排序:
As Jan stated in their comment, you can also sort the values before imploding it using ORDER BY:
SELECT person_id,
GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
正如 Dag 在他的评论中所述, 结果有 1024 字节的限制.要解决此问题,请在查询之前运行此查询:
As Dag stated in his comment, there is a 1024 byte limit on the result. To solve this, run this query before your query:
SET group_concat_max_len = 2048;
当然,您可以根据需要更改2048.计算和赋值:
Of course, you can change 2048 according to your needs. To calculate and assign the value:
SET group_concat_max_len = CAST(
(SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
FROM peoples_hobbies
GROUP BY person_id) AS UNSIGNED);
这篇关于我可以将多个 MySQL 行连接到一个字段中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何有效地使用窗口函数根据 N 个先前值来决定How to use windowing functions efficiently to decide next N number of rows based on N number of previous values(如何有效地使用窗口函数根据
在“GROUP BY"中重用选择表达式的结果;条款reuse the result of a select expression in the quot;GROUP BYquot; clause?(在“GROUP BY中重用选择表达式的结果;条款?)
Pyspark DataFrameWriter jdbc 函数的 ignore 选项是忽略整Does ignore option of Pyspark DataFrameWriter jdbc function ignore entire transaction or just offending rows?(Pyspark DataFrameWriter jdbc 函数的 ig
使用 INSERT INTO table ON DUPLICATE KEY 时出错,使用 Error while using INSERT INTO table ON DUPLICATE KEY, using a for loop array(使用 INSERT INTO table ON DUPLICATE KEY 时出错,使用 for 循环数组
pyspark mysql jdbc load 调用 o23.load 时发生错误 没有合pyspark mysql jdbc load An error occurred while calling o23.load No suitable driver(pyspark mysql jdbc load 调用 o23.load 时发生错误 没有合适的
如何将 Apache Spark 与 MySQL 集成以将数据库表作为How to integrate Apache Spark with MySQL for reading database tables as a spark dataframe?(如何将 Apache Spark 与 MySQL 集成以将数据库表作为