USER 表
userDeviceId | userCode | channelId | ...
-------------|----------|-----------|-----
dev001 | userA | 301040 |
dev001 | userB | 301040 | <-- 同一 deviceId 對應多 userCode
dev002 | userC | 301040 |
dev003 | userD | 301040 |
dev003 | userE | 301040 |
dev003 | userF | 301040 | <-- 三筆
找出 channelId = '301040' 且 **同一 userDeviceId 對應 2 筆以上 userCode** 的所有記錄。
SELECT *
FROM `USER`
WHERE `userDeviceId` IN (
SELECT `userDeviceId`
FROM `USER`
WHERE `channelId` = '301040'
GROUP BY `userDeviceId`
HAVING COUNT(*) >= 2
);
channelId='301040' 的資料,按 userDeviceId 分組,HAVING COUNT(*) >= 2 保留出現 ≥2 次的裝置 ID。userDeviceId 的完整記錄 (含 userCode 等欄位)。CREATE INDEX idx_channel_device ON USER(channelId, userDeviceId); 覆蓋子查詢所需欄位,避免全表掃描。SELECT u.*
FROM `USER` u
JOIN (
SELECT `userDeviceId`
FROM `USER`
WHERE `channelId` = '301040'
GROUP BY `userDeviceId`
HAVING COUNT(*) >= 2
) d ON u.`userDeviceId` = d.`userDeviceId`;
SELECT COUNT(DISTINCT userDeviceId) ...。HAVING COUNT(*) = 1
同理可得。