In MySql DB I have a deviceBindingInfo table contains userId and deviceType, How to select all userId who has binded all the deviceTypes{A, B, C}
Is the following solution correct? Or is there a better solution?
SELECT userId
FROM (SELECT userId, deviceType
FROM deviceBindingInfo
WHERE deviceType IN (A, B, C)
GROUP BY userId, deviceType) AS TempTable
GROUP BY userId
HAVING COUNT(userId) >= 3;
You should not use group without aggregation function by for remove duplicate in inner select , you can use DISTINCT for this and for get the correct count you should use count(deviceType) (in this case the result is the same .. but rae th deviceType that match for A,B,C)
SELECT userId
FROM (
SELECT
distinct userId
, deviceType
FROM deviceBindingInfo
WHERE deviceType IN (A, B, C)
) AS TempTable
GROUP BY userId HAVING COUNT(deviceType) >= 3;
or you can do withou subquery using count(distinct deviceType)
SELECT
userId
FROM deviceBindingInfo
WHERE deviceType IN (A, B, C)
group by userId
HAVING COUNT(deviceType) >= 3;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.