Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从多个MySQL表中获取两个用户的共享联系人_Mysql_Sql - Fatal编程技术网

从多个MySQL表中获取两个用户的共享联系人

从多个MySQL表中获取两个用户的共享联系人,mysql,sql,Mysql,Sql,我的MySQL数据库中有两个表 第一个存储用户列表,另一个存储每个用户的联系人列表 用户表: +----+----------+--------------+ | id | name | phoneNumber | +----+----------+--------------+ | 1 | David | 661-618-5436 | | 2 | Sarah | 818-526-4830 | | 3 | Suzan | 323-623-3493 | +----

我的MySQL数据库中有两个表

第一个存储用户列表,另一个存储每个用户的联系人列表

用户表:

+----+----------+--------------+
| id |   name   | phoneNumber  |
+----+----------+--------------+
|  1 | David    | 661-618-5436 |
|  2 | Sarah    | 818-526-4830 |
|  3 | Suzan    | 323-623-3493 |
+----+----------+--------------+
联系人表:

+----+-----------------+--------+--------------+
| id | belongsToUserId |  name  | phoneNumber  |
+----+-----------------+--------+--------------+
|  1 |               1 | Gerard | +18185329384 |
|  2 |               1 | Austin | +18739283847 |
|  3 |               2 | Jamie  | +15655468907 |
|  4 |               2 | Jade   | +19893828192 |
|  5 |               3 | Phil   | +18786754234 |
|  6 |               3 | Duke   | +18765467832 |
|  7 |               3 | Gerard | +18185329384 |
|  8 |               3 | Jade   | +19893828192 |
+----+-----------------+--------+--------------+
我想做的是创建一个查询,该查询有效地获取两个用户ID,并通过
phoneNumber
返回这两个用户的常用联系人

例如:用户ID
1
3
在他们的联系人中都有
Gerard+18185329384
,因此查询将只返回他

对于这种任务,什么是最有效的查询


谢谢:)

以下选择将为您提供拥有1个以上用户的所有联系人

  SELECT Contacts.name, Contacts.phoneNumber
    FROM Users INNER JOIN Contacts ON (Users.id = Contacts.belongsToUserId)
GROUP BY Contacts.name, Contacts.phoneNumber
  HAVING COUNT (*) > 1
您想要自联接:

select c1.name, c1.phonenumber
from contacts c1 join
     contacts c2
     on c1.name = c2.name and c1.phonenumber = c2.phonenumber and
        c1.belongsToUserId = 1 and
        c2.belongsToUserId = 3;

以下查询将显示共享联系人以及拥有普通联系人的
UseID

如果您只想显示共享联系人的详细信息,则可以跳过前两列

select min(belongsToUserId) as User1,
       max(belongsToUserId) as User2,
       name,
       phone Number
from contacts
group by name,phoneNumber
having count(*) > 1;

如果我正确理解了你的问题,我想这可能就是你想要的:

SELECT 
    c1.id, 
    c1.belongsToUserId, 
    c1.phoneNumber, 
    c1.name 
FROM 
    Contacts c1
JOIN 
    Contacts c2 ON (c1.phoneNumber=c2.phoneNumber AND c2.userId=3)
WHERE 
    c1.belongsToUserId =1

工作起来很有魅力,很整洁。谢谢!:)
SELECT 
    c1.id, 
    c1.belongsToUserId, 
    c1.phoneNumber, 
    c1.name 
FROM 
    Contacts c1
JOIN 
    Contacts c2 ON (c1.phoneNumber=c2.phoneNumber AND c2.userId=3)
WHERE 
    c1.belongsToUserId =1