首页 > 解决方案 > SQL 查询中的列数

问题描述

我想COUNT(item_id)在此声明:

SELECT * FROM `notifications` WHERE `uid` = '3' AND `seen` = '0' AND id IN (
SELECT MAX(id), COUNT(item_id)
FROM `notifications`
GROUP BY item_id
)  ORDER BY id DESC

但是发生了这个错误:操作数应该包含 1 列。

桌子:

[id] [uid] [item_id] [seen]
 1     3       69       0
 2     3       69       0
 3     3       70       0
 4     3       69       0
 5     3       70       0
 6     3       69       0

预期输出:(Order BY id DESC)其中69是最后一条记录。

[item_id] [num]
    69      4
    70      2

标签: mysqlsql

解决方案


有根据的猜测说你想要一个JOIN

SELECT n.*, nmax.cnt
FROM notifications n JOIN
     (SELECT item_id,  MAX(id) as max_id, COUNT(item_id) as cnt
      FROM notifications
      GROUP BY item_id
     ) nmax
     ON n.item_id = nmax.item_id AND nmax.id = nmax.max_id
WHERE n.uid = 3 AND n.seen = 0  -- removed the single quotes because these are probably numbers
ORDER BY n.id DESC;

目前尚不清楚您是否也需要子查询中的过滤条件。


推荐阅读