簡體   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