使用MySQL,我可以执行以下操作:
SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;
我的输出:
shopping
fishing
coding
但我只想要1行1列:
预期输出:
shopping, fishing, coding
原因是我从多个表中选择了多个值,在所有的连接之后,我得到了比我想要的多得多的行。
我在MySQL Doc上查找了一个函数,它看起来不像CONCAT或CONCAT_WS函数接受结果集。
这里有人知道怎么做吗?
这里,我的意图是在不使用group_concat()函数的情况下应用字符串连接:
Set @concatHobbies = '';
SELECT TRIM(LEADING ', ' FROM T.hobbies ) FROM
(
select
Id, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbies
from peoples_hobbies
)T
Order by Id DESC
LIMIT 1
Here
select
Id, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbies
from peoples_hobbies
将返回
Id hobbies
1 , shopping
2 , shopping, fishing
3 , shopping, fishing, coding
现在我们的预期结果是第三。所以我用
Order by Id DESC
LIMIT 1
然后我也将第一个“,”从字符串中删除
TRIM(LEADING ', ' FROM T.hobbies )
现在已经很晚了,但对于那些正在搜索“使用透视表将多个MySQL行连接到一个字段中”的人来说会很有帮助:)
查询:
SELECT pm.id, pm.name, GROUP_CONCAT(c.name) as channel_names
FROM payment_methods pm
LEFT JOIN payment_methods_channels_pivot pmcp ON pmcp.payment_method_id = pm.id
LEFT JOIN channels c ON c.id = pmcp.channel_id
GROUP BY pm.id
桌子
payment_methods
id | name
1 | PayPal
channels
id | name
1 | Google
2 | Faceook
payment_methods_channels_pivot
payment_method_id | channel_id
1 | 1
1 | 2
输出: