MySQL:在不使用Distinct的情况下自己加入表

时间:2011-06-24 16:11:33

标签: mysql sql

这是我的表结构

  • fName 朋友的名字[Varchar]
  • fUID 朋友的ID [Int]
  • UID 用户ID [Int]

pk [fUID,UID]

我想得到两个人的共同朋友。我试过了:

SELECT t1.fName,
       t1.fUID 
  FROM friends t1, 
       friends t2 
 WHERE t1.UID = X 
   AND t2.UID = X2

但它不起作用:(我反复得到相同的结果。

一些示例数据

UID  Name  
----------
1    Mark  
2    Eduardo  
3    Dustin  

Friend Table

UID  fUID  fName  
------------------
1    2     Eduardo   
2    1     Mark  
3    1     Mark  
1    3     Dustin 

5 个答案:

答案 0 :(得分:1)

如果我理解正确,您有两个用户ID(X1和X2),并且您想要找到与这两个人都是朋友的所有人。

SELECT f1.fUID, f1.fName
FROM friends f1,
friends f2
WHERE f1.UID = X1
      AND f2.UID = X2
      AND f1.fUID = f2.fUID

注意:这假设所有朋友关系在friends表中存储两次,每个方向一次。如果没有,它会变得更复杂。

答案 1 :(得分:0)

试试这个:

   SELECT DISTINCT t1.fName,t1.fUID 
     FROM friends t1, friends t2 
    WHERE t1.UID=<USER-ID-1>
      AND t2.UID=<USER-ID-2>
      AND t1.fUID = t2.fUID
      AND t1.UID <> t2.UID

测试数据设置:

CREATE TABLE Friends
(
    uID INT,
    fuID INT,
    fName VARCHAR(20)
)

INSERT INTO Friends
SELECT '1 ',' 2 ','Eduardo'
UNION
SELECT '2 ',' 1 ','Mark'
UNION
SELECT '3 ',' 1 ','Mark'
UNION
SELECT '1 ',' 3 ','Dustin' 


SELECT DISTINCT t1.fName,t1.fUID 
    FROM Friends t1, Friends t2 
 WHERE t1.UID=2
   AND t2.UID=3
     AND t1.fUID = t2.fUID

答案 2 :(得分:0)

SELECT t1.fName, t1.fUID FROM friends t1 WHERE t1.UID=X1
Union
SELECT t1.fName, t1.fUID FROM friends t1 WHERE t1.UID=X2

您可以使用联合查询来获取共同的朋友。

答案 3 :(得分:0)

select fName
from friends
where uid = FIRST_USER_ID
  and exists (
    select 1
    from friends sfriends
    where sfriends.fid = friends.fid
      and sfriends.uid = SECOND_USER_ID
);

答案 4 :(得分:0)

SELECT
  f.fUID,
  u.Name
FROM (
  SELECT fUID
  FROM (
    SELECT
      CASE WHEN UID  IN (@X, @X2) THEN UID ELSE fUID END AS UID,
      CASE WHEN fUID IN (@X, @X2) THEN UID ELSE fUID END AS fUID
    FROM friends
    WHERE     (UID IN (@X, @X2) OR  fUID IN (@X, @X2))
      AND NOT (UID IN (@X, @X2) AND fUID IN (@X, @X2))
  ) s
  GROUP BY fUID
  HAVING COUNT(DISTINCT UID) = 2
) f
  INNER JOIN users u ON f.fUID = u.UID