简体   繁体   English

SQL查询中的列数

[英]Column count in a SQL Query

I want to put COUNT(item_id) in this statement: 我想在此语句中放入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

But This error occurred: Operand should contain 1 column(s). 但是发生此错误: 操作数应包含1列。

Table: 表:

[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

Expected output: (Order BY id DESC) where 69 is the last record. 预期输出: (Order BY id DESC),其中69是最后一条记录。

[item_id] [num]
    69      4
    70      2

An educated guess says that you want a JOIN : 有根据的猜测说您想要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;

It is unclear whether you want the filtering conditions in the subquery as well. 还不清楚您是否还需要子查询中的过滤条件。

Given your sample data and expected results, there's no need for a subquery: 根据您的样本数据和预期结果,无需子查询:

select item_id, count(*)
from notifications
group by item_id
where uid = 3 and seen = 0
order by max(id) desc;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM