子查询的解决方案返回超过1行

时间:2017-09-06 12:36:30

标签: php mysql sql

我有以下查询过去按预期工作,最近随着记录数量的增加,不知何故返回#1242 - Subquery returns more than 1 row

SELECT `log`.id,log.account_id,log.type, 
( SELECT COUNT(*) FROM instagram_log as LIKES WHERE `account_id`=log.account_id AND `type`='like' AND log.target_account=LIKES.target_account AND `seen`=0 ) as has_liked, 
( SELECT COUNT(*) FROM instagram_log as Comments WHERE `account_id`=log.account_id AND `type`='comment' AND log.target_account=Comments.target_account AND `seen`=0 ) as has_commented, 
( SELECT information FROM instagram_log as Source WHERE `account_id`=log.account_id AND `type`='follow' AND log.target_account=Source.target_account AND `seen`=0 ) as source, 
( SELECT data FROM instagram_accounts WHERE `id`=log.account_id ) as InstagramInfo 
FROM `instagram_log` as `log` WHERE `type` = 'follow_back' AND `account_id` IN('1', '5', '2')  ORDER BY `id` DESC LIMIT 15

2 个答案:

答案 0 :(得分:1)

添加" LIMIT 1"在子查询中可以返回多于1行,或者在select中使用agregate函数(MAX,MIN,GROUP_CONCAT ...)

答案 1 :(得分:1)

SELECT `log`.id,log.account_id,log.type, 
( SELECT COUNT(*) FROM instagram_log as LIKES WHERE 
`account_id`=log.account_id AND `type`='like' AND 
log.target_account=LIKES.target_account AND `seen`=0 ) as has_liked, 
( SELECT COUNT(*) FROM instagram_log as Comments WHERE 
`account_id`=log.account_id AND `type`='comment' AND 
log.target_account=Comments.target_account AND `seen`=0 ) as has_commented, 
( SELECT information FROM instagram_log as Source WHERE 
`account_id`=log.account_id AND `type`='follow' AND 
log.target_account=Source.target_account AND `seen`=0 limit 1) as source, 
( SELECT data FROM instagram_accounts WHERE `id`=log.account_id limit 1) as 
InstagramInfo 
FROM `instagram_log` as `log` WHERE `type` = 'follow_back' AND `account_id` 
IN('1', '5', '2')  ORDER BY `id` DESC LIMIT 15

试试这个..