4

我正在挠头想找出以下问题的解决方案:

我有一个包含两个字段 USER_ID 和 CLIENT_ID 的表。对于每个 USER_ID,有 1 到 n 个 CLIENT_ID。

假设用户 A 链接到客户端 1,2 和 3。我想构建一个查询,该查询返回也链接到所有这些客户端的其他用户。它们可能链接到更多客户端,但它们必须链接到用户 A 的所有客户端。

示例:用户 B 具有指向客户端 1、2、3、4 的链接。用户 C 具有到客户端 1,2 的链接。然后查询应该返回用户 B,因为用户 B 具有指向用户 A 的所有客户端的链接。不应返回用户 C,因为他只有与用户 A 的部分而不是全部客户端的链接。

这似乎是一个看似简单的问题,但我一生都无法提出满足我的约束的查询。有经验的 SQL 大师可以帮助我吗?

4

2 回答 2

3

做出许多名称和数据类型假设...

DECLARE
  @UserId  int
 ,@ClientCount  int

DECLARE @Clients as table
 (ClientId  int  not null)

--  All clients for the "target" user
INSERT @Clients
 select Clientid
 from MyTable
 where UserId = @userId

--  Track how many there are
SET @ClientCount = @@rowcount

--  List all users that have those clients
SELECT mt.UserId, count(*) HowMany
 from Mytable mt
  inner join @Clients cl
   on cl.ClientId = mt.Clientid
 where UserId <> @UserId
 group by mt.UserId
 having count(*) = @ClientCount

我没有一个表来测试这个,但它应该几乎不需要调试。

于 2010-03-11T15:22:22.977 回答
2
SELECT uc.user_id, u.username, COUNT(*) as client_count
FROM user u
INNER JOIN user_client uc
USING (user_id)
WHERE uc.client_id IN (
  SELECT client_id
  FROM   user_client
  WHERE  user_id = {ID of user A}
)
GROUP BY uc.user_id, u.username
HAVING client_count = (
  SELECT COUNT(*)
  FROM   user_client
  WHERE  user_id = {ID of user A}
)

未经测试,可能是特定于 MySQL 的,但这样的东西应该可以工作。

于 2010-03-11T14:18:53.877 回答