子查询将多个记录作为对象数组返回到mysql中的一个字段

时间:2017-11-03 09:18:32

标签: php mysql

我正在尝试以下查询,其中子查询将返回多个记录。

SELECT count(*) as total, GROUP_CONCAT ( SELECT `id`, `lead_id`, `transaction_id`, `status`, `created_at` FROM `payments` WHERE `user_id` = '7') as data FROM `payments`WHERE `user_id` = '7'

但它会返回以下错误

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT `id`, `lead_id`, `transaction_id`, `status`, `created_at` FROM `payments`' at line 1

请帮我解决此问题

2 个答案:

答案 0 :(得分:0)

您需要以相反的方式使用查询,例如:

SELECT `id`, `lead_id`, `transaction_id`, `status`, `created_at`, 
(SELECT count(*) FROM `payments` WHERE `user_id` = '7') AS `total`
FROM `payments` WHERE `user_id` = '7';

您无法在子查询中将记录数组作为一条记录返回。最好单独读取记录并在应用程序中对它们进行计数(或将计数作为查询中的另一个值读取)。

答案 1 :(得分:0)

为什么不简化呢?

SELECT `id`, `lead_id`, `transaction_id`, `status`, `created_at`, count(*) 
AS `total` FROM `payments` WHERE `user_id` = '7'
GROUP BY `id`, `lead_id`, `transaction_id`, `status`, `created_at`;

无论如何你想要实现什么?提供一些样本数据和数据,你试着去。