2013-06-05 182 views
2

我在MySQL表cart上有这些数据。MySQL group_concat和concat

enter image description here

我想运行一个查询,将这样的输出:

Advance Technique Conditioner (2), Advance Technique Gel (1)

所以我在做一个group_concat查询,并试图查询到我的输出所需的输出。这是输出的最接近查询所需:

select concat(group_concat(product separator ', '), group_concat(quantity separator ', ')) as 'prod' from cart where debt_no='0000001'

但如预期,它输出的是这样的:Advance Technique Conditioner, Advance Technique Gel2, 1

我怎样才能得到需要的结果?

回答

5

CONCAT()应该是内部GROUP_CONCAT()

GROUP_CONCAT(CONCAT(product, ' (', CAST(quantity AS CHAR(15)), ')') SEPARATOR ', ') 

记得,GROUP_CONCAT()默认长度为1024。所以,如果你想改变限制执行以下行,

SET [GLOBAL | SESSION] group_concat_max_len = val; -- val is the new length 
+0

是的,我试过这个,我想知道为什么输出是'[BLOB - 60B]'。所以这就是为什么。当我尝试执行上述行时出现错误。 – xjshiya

+0

哦,那么你应该首先转换数量,因为它是一个数字。我将更新答案 –

+0

更新后的查询现在正在输出正常!非常感谢!但是在执行这个SET [GLOBAL |时,我仍然有错误SESSION] group_concat_max_len = 5000;' – xjshiya

1
SELECT GROUP_CONCAT(CONCAT(product, ' (', quantity, ')') SEPARATOR ', ') 
1

你首先需要做concat(),然后group_concat()

select group_concat(concat(product, ' (', quantity, ')') separator ', ') as prod 
from cart where debt_no='0000001'