【问题标题】:SQL query for returning multiple fields joined to the same reference用于返回连接到同一引用的多个字段的 SQL 查询
【发布时间】:2013-04-11 13:52:27
【问题描述】:

所以我有下表,do_stock_movement,看起来像这样:

stock_movement_id sm_number sm_source_id sm_destination_id 15164b86a7533d 145 1516478840ee29 151644d8bd63f2 15166b89d1a9fc 194 15165c481bd9d0 151659e632cd48

sm_source_idsm_destination_id 列都参考存储在 do_product_points 中的产品点。

我正在使用以下 SQL 查询:

选择 * 从 do_stock_movement INNER JOIN do_product_points ON product_points_id = sm_source_id WHERE sm_number = '145'

do_product_points 中,有一个名为pp_name 的字段。我需要sm_source_idsm_destination_id 对应的pp_name

但是,如果您将连接字段更改为 sm_source_idsm_destination_id,上述查询只会返回 pp_name

什么 SQL 查询将为sm_source_idsm_destination_id 返回对应的pp_name

我希望这很清楚。如果不是,请提出问题!

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    JOIN这张表do_product_points再换一次sm_destination_id

    SELECT 
      s.pp_name AS SourcePoint,
      d.pp_name AS DestinationPoint,
      ...
    FROM do_stock_movement AS m
    INNER JOIN do_product_points s ON s.product_points_id = m.sm_source_id
    INNER JOIN do_product_points d ON d.product_points_id = m.sm_destination_id
    WHERE m.sm_number = '145'
    

    【讨论】:

      【解决方案2】:

      你需要加入两次并使用别名:

      SELECT *, Src.pp_name, Dst.pp_name FROM do_stock_movement
        INNER JOIN do_product_points as Src 
            ON Src.product_points_id = sm_source_id
        INNER JOIN do_product_points as Dst 
            ON Dst.product_points_id = sm_destination_id
      

      【讨论】:

        【解决方案3】:

        您需要加入product_points 表两次,一次使用source_id,一次使用destination_id:

        SELECT * FROM do_stock_movement move
        INNER JOIN do_product_points source ON source.product_points_id = move.sm_source_id
        INNER JOIN do_product_points dest ON dest.product_points_id = move.sm_destination_id
        WHERE sm_number = '145'
        

        【讨论】:

          猜你喜欢
          • 2017-06-02
          • 1970-01-01
          • 1970-01-01
          • 2011-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-23
          相关资源
          最近更新 更多