You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查找全量日志中插入记录数为0的设备ID及SQL报错解决

Fixing the "Subquery returned more than 1 value" Error & Finding Devices with Zero Inserted Records

Hey there! Let's tackle this problem step by step. First, let's clear up why you're getting that annoying error:

Why the Error Happens

That error pops up when you use a comparison operator like =, !=, <, etc., with a subquery that returns multiple values. For example, if you tried something like:

SELECT DeviceID FROM LogTable WHERE DeviceID = (SELECT DeviceID FROM LogTable WHERE RecordInserted > 0)

The subquery inside returns every device that has at least one non-zero insert count—so multiple IDs. Using = here doesn't make sense, since you can't compare a single value to a list of values. That's exactly what's triggering the error.

Correct SQL to Find Devices with Always Zero Inserted Records

Your goal is to find devices where every single entry in the log has RecordInserted = 0. Here are two reliable ways to do this:

Approach 1: Use NOT EXISTS (Great for clarity)

This query filters out any device that has even one entry with a non-zero insert count:

SELECT DISTINCT DeviceID
FROM LogTable
WHERE NOT EXISTS (
    SELECT 1
    FROM LogTable AS LT
    WHERE LT.DeviceID = LogTable.DeviceID
    AND LT.RecordInserted > 0
)
  • DISTINCT ensures you get each device ID only once, even if it has multiple log entries.
  • The subquery checks if there's any record for the same device where inserts were greater than 0. If there isn't, the device stays in the result set.

Approach 2: Use GROUP BY + HAVING (Concise and efficient)

This groups all log entries by device, then checks if the maximum insert count for that device is 0 (meaning no entry ever had a non-zero value):

SELECT DeviceID
FROM LogTable
GROUP BY DeviceID
HAVING MAX(RecordInserted) = 0
  • GROUP BY DeviceID aggregates all records for each device.
  • HAVING MAX(RecordInserted) = 0 filters out any device that ever had an insert count greater than 0 (since their max would be higher than 0).

Which One to Choose?

  • Use NOT EXISTS if you want a query that's easy to read and modify later (like adding more filters to the subquery).
  • Use GROUP BY + HAVING if you prefer a shorter query, and your database optimizes aggregate functions well.

内容的提问来源于stack exchange,提问作者krishna mohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:12:02