代码之家  ›  专栏  ›  技术社区  ›  Johan Sánchez

从哪里获取数据Postgresql

  •  1
  • Johan Sánchez  · 技术社区  · 9 年前

    我有这张桌子: users contacts user_providers ,这是每一个的结构:

    enter image description here

    enter image description here

    enter image description here

    我想从contacts表中的特定用户id和user\u provider中的user\u provider\u name中获取所有联系人,我有这个查询

    SELECT c.id, c.contact_name,c.description,c.discharge,c.latitude,c.longitude,c.town,c.country,c.province,
      (SELECT array_agg(DISTINCT cn.number) FROM contact_numbers cn WHERE cn.contact_id = c.id) AS numbers,
      (SELECT array_agg(DISTINCT ce.email)  FROM contact_emails  ce WHERE ce.contact_id = c.id) AS emails
      FROM
       contacts c,
       user_providers po
      WHERE
       c.user_id = 1 and po.provider_name = 'google'
      ORDER BY
       c.id;
    

    enter image description here

    查询不尊重provider\u名称,它返回仅与特定用户id相关的所有联系人。

    接触稳定 enter image description here user\u provider表 enter image description here

    谢谢你的帮助!

    2 回复  |  直到 9 年前
        1
  •  1
  •   tima user8609645    9 年前

    根据我的评论,您得到的查询结果是正确的,因为表 contacts user_providers 除了 user_id

    用户id 中的所有三行都是相同的 number of contacts for specific user id * number of user providers for a specific user id

    例如,在没有 provider_name 在where子句中,获取您:3(联系人)*2(提供者)

    id  contact_name  provider_name
    -------------------------------
    1   Vacio         google
    2   Vacio2        google
    3   Vaciogiogle   google
    1   Vacio         facebook
    2   Vacio2        facebook
    3   Vaciogiogle   facebook
    

    联络 user\u提供程序 桌子。例如,添加 provider_id 表中存储提供者的ID 桌子然后,您可以使用下面的SQL连接表,并在 提供商名称

    SELECT c.id, c.contact_name, up.provider_name 
    FROM contacts c 
    LEFT JOIN user_providers up ON c.provider_id = up.provider_id 
    WHERE c.user_id = 1 AND up.provider_name = 'google';
    
        2
  •  0
  •   Gordon Linoff    9 年前

    JOIN 从不 在中使用逗号 FROM 总是 使用适当、明确的 加入

    SELECT up.user_id, c.contact_name
    FROM contacts c JOIN
         user_providers up
         ON c.id = up.user_id
    WHERE up.user_id = 1 AND up.provider_name = 'facebook'       
    ORDER BY up.user_id;
    

    然而