如何强制子查询只返回一行?

时间:2018-04-06 09:14:23

标签: mysql sql

这是我的问题:

SELECT e.id, e.table_code,

 ( SELECT MIN(date_time) date_time,
         SUM(score) score,
         type,
         post_id,
         table_code,
         comment_id,
         context
   FROM events 
   WHERE author_id = 32
   GROUP BY type, post_id, table_code, comment_id, context
   ORDER BY MIN(date_time) DESC
   LIMIT 15 ) g

FROM events e
WHERE e.author_id = 32 AND e.date_time >= MIN(g.date_time)
ORDER BY seen ASC, date_time DESC 

它抛出:

  

#1241 - 操作数应包含1列

我知道如何解决它?

我正在努力:

  1. 选择15组最新事件(组中最小的id)
  2. 然后选择id为最小id的所有事件(属于特定用户)
  3. 注意到,可能“群体”含糊不清。实际上它是关于通知的,因此具有相同帖子ID(并且与投票相关)的通知将被加总并命名为一个组。

1 个答案:

答案 0 :(得分:0)

您可以使用LEFT JOIN代替Sub-Query

试试这个:

SELECT e.id, e.table_code,g.*
FROM events e
LEFT JOIN (SELECT MIN(date_time) date_time,
         SUM(score) score,
         type,
         post_id,
         table_code,
         comment_id,
         context
   FROM events 
   WHERE author_id = 32
   GROUP BY type, post_id, table_code, comment_id, context
   ORDER BY MIN(date_time) DESC
   LIMIT 15 ) g ON e.table_code = g.table_code AND e.date_time >= g.date_time
WHERE e.author_id = 32
ORDER BY seen ASC, e.date_time DESC