加入多个唯一键表但只返回一行

时间:2018-04-25 05:29:41

标签: mysql sql inner-join

我的导入列表如下表import_order pk:import_date ,import_no, product_id

--------------------------------------------------------------------------
import_date | import_no | product_id | supplier_id | purchase_cost | qty |
--------------------------------------------------------------------------
2018-01-02  | M0001     | p00001     | s00001      | 2500          | 7   |
2018-01-02  | M0001     | p00002     | s00001      | 2700          | 4   |
2018-01-02  | M0001     | p00003     | s00001      | 3500          | 5   |
--------------------------------------------------------------------------

我想通过下表

加入供应商详细信息
supplier_detail

-------------------------------------------------
 supplier_id | supplier_name   | tel            |
-------------------------------------------------
 s00001      | DevelopGlasses  | +11254421478   |
 s00002      | Operalise       | +11252232547   |
 s00003      | Azuing          | +11245454478   |
-------------------------------------------------

我想查询是这样的结果

--------------------------------------------------------------------------------
import_date | import_no| product_id | supplier_id| supplier_name| tel          |
--------------------------------------------------------------------------------
2018-01-02  | M0001    | p00001     | s00001     |DevelopGlasses|+11254421478  |
2018-01-02  | M0001    | p00002     | s00001     |DevelopGlasses|+11254421478  |
2018-01-02  | M0001    | p00003     | s00001     |DevelopGlasses|+11254421478  |
--------------------------------------------------------------------------------

这是我的sql

SELECT i.*,s.* FROM import_order i INNER JOIN supplier_detail s ON i.s_id = s.s_id

结果是

--------------------------------------------------------------------------------
import_date | import_no| product_id | supplier_id| supplier_name| tel          |
--------------------------------------------------------------------------------
2018-01-02  | M0001    | p00001     | s00001     |DevelopGlasses|+11254421478  |
--------------------------------------------------------------------------------

2 个答案:

答案 0 :(得分:0)

您需要将on条件更正为

SELECT i.import_date, i.import_no, i.product_id, 
       i.supplier_id, s.supplier_name, s.tel    
FROM import_order i 
INNER JOIN supplier_detail s 
      ON i.supplier_id = s.supplier_id; -- instead of i.s_id = s.s_id

答案 1 :(得分:0)

仅使用左连接,内连接选择相关记录

SELECT i.*,s.* FROM import_order i LEFT JOIN supplier_detail s ON i.s_id = s.s_id