繁体   English   中英

在MySQL中,如何获取相同外键的所有值都显示在另一个列的列表中的记录

[英]In Mysql how to get records which for the same foreign key has all values showed up in a list for another col

在MySql DB中,我有一个deviceBindingInfo表,其中包含userId和deviceType,如何选择已绑定所有deviceTypes {A,B,C}的所有userId

以下解决方案正确吗? 还是有更好的解决方案?

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;

您不应该使用没有聚合功能的组来删除内部select中的重复项,您可以为此使用DISTINCT并获得正确的计数,而应使用count(deviceType)(在这种情况下,结果相同。匹配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;

或者您可以使用count(distinct deviceType)进行子查询

      SELECT 
        userId
      FROM deviceBindingInfo 
      WHERE deviceType IN (A, B, C) 
      group by userId
      HAVING COUNT(deviceType) >= 3;

暂无
暂无

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

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