【问题标题】:select distinct from two tables从两个表中选择不同的
【发布时间】:2012-06-14 11:17:54
【问题描述】:

给定以下表格

      orders
      +----+---------+---------+
      | id | user_id | details |
      +----+---------+---------+  
      | 1  |    2    | blue    | 
      +----+---------+---------+
      | 2  |    1    | red     | 
      +----+---------+---------+
      | 3  |    2    | yellow  | 
      +----+---------+---------+
      | 4  |    2    | cyan    | 
      +----+---------+---------+

      users
      +---------+---------+---------+
      | user_id |    ph   |   name  | 
      +---------+---------+---------+
      |   1     |   123   |   fred  | 
      +---------+---------+---------+
      |   2     |   456   |   Stan  | 
      +---------+---------+---------+
      |   3     |   189   |   Levi  | 
      +---------+---------+---------+

我知道如何使用 distinct 在第一个表中只选择每个用户的一次出现

     SELECT DISTINCT user_id FROM orders

我怎样才能只从用户那里提取电话号码?

我可能会循环并挑选出每个数字,例如...

     SELECT ph from users WHERE user_id = user_id

不禁想到我可以使用一个单行查询。

结果是

     123
     456

【问题讨论】:

    标签: mysql


    【解决方案1】:

    从 Orders 表中进行选择可能是一项繁重的操作。取决于该表将变得多大。

    也许这个会更快:

    Select u.ph 
      from users u 
      where exists (select id from orders where user_id = u.user_id);
    

    【讨论】:

      【解决方案2】:

      相关子查询将比使用 JOIN 完成时慢得多,如果您定义了索引,则可以加入索引:

      SELECT
          a.ph
      FROM
          users a
      INNER JOIN
          orders b ON a.user_id = b.user_id
      GROUP BY
          a.user_id,
          a.ph
      

      【讨论】:

        猜你喜欢
        • 2016-05-14
        • 1970-01-01
        • 1970-01-01
        • 2012-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-22
        • 2017-01-26
        相关资源
        最近更新 更多