我有这个查询:
SELECT
tud.detail_company_name AS company_name,
tud.detail_country AS company_country,
trv.review_title AS review_title
FROM users_detail tud
INNER JOIN users_auth tua
ON tud.user_id = tua.user_id
LEFT JOIN reviews trv
ON tud.user_id = trv.review_company_id
WHERE
tua.auth_user_type = "company" OR tua.auth_user_type = "guestcompany"
查询工作正常,它返回如下结果:
Array
(
[0] => Array
(
[company_name] => The Coffee Brewery
[company_country] => US
[review_title] =>
)
[1] => Array
(
[company_name] => Crea Nail Art Studio
[company_country] => SG
[review_title] =>
)
[2] => Array
(
[company_name] => Hello Mall
[company_country] => JP
[review_title] => Fake goods!
)
[3] => Array
(
[company_name] => Hello Mall
[company_country] => JP
[review_title] => Never buy in there!
)
)
正如您所注意到的,数组键 2 和 3 具有相同的 company_name,但 review_title 不同。是否有可能必须将其连接到一个结果中并用逗号分隔?举例来说这个结果:
Array
(
[0] => Array
(
[company_name] => The Coffee Brewery
[company_country] => US
[review_title] =>
)
[1] => Array
(
[company_name] => Crea Nail Art Studio
[company_country] => SG
[review_title] =>
)
[2] => Array
(
[company_name] => Hello Mall
[company_country] => JP
[review_title] => Fake goods!, Never buy in there!
)
)
编辑
如果响应是这样怎么办:
Array
(
[0] => Array
(
[company_name] => The Coffee Brewery
[company_country] => US
[review_title] =>
[review_approved] =>
)
[1] => Array
(
[company_name] => Crea Nail Art Studio
[company_country] => SG
[review_title] =>
[review_approved] =>
)
[2] => Array
(
[company_name] => Hello Mall
[company_country] => JP
[review_title] => Fake goods!
[review_approved] => 1
)
[3] => Array
(
[company_name] => Hello Mall
[company_country] => JP
[review_title] => Never buy in there!
[review_approved] => 0
)
)
如何才能不在 review_title GROUP_CONCAT
中包含 0 review_approved?那么它会输出这样的吗?
Array
(
[0] => Array
(
[company_name] => The Coffee Brewery
[company_country] => US
[review_title] =>
)
[1] => Array
(
[company_name] => Crea Nail Art Studio
[company_country] => SG
[review_title] =>
)
[2] => Array
(
[company_name] => Hello Mall
[company_country] => JP
[review_title] => Fake goods!
)
)
最佳答案
是的。使用GROUP_CONCAT()
:
SELECT
tud.detail_company_name AS company_name,
tud.detail_country AS company_country,
GROUP_CONCAT(trv.review_title SEPARATOR ',') AS review_titles
FROM users_detail tud
INNER JOIN users_auth tua
ON tud.user_id = tua.user_id
LEFT JOIN reviews trv
ON tud.user_id = trv.review_company_id
WHERE
tua.auth_user_type = :company OR tua.auth_user_type = :guestcompany
GROUP BY
tud.detail_company_name,
tud.detail_country;
关于mysql - 合并结果并用逗号分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14036834/