如何在MYSQL中合并多表

时间:2017-09-25 12:37:07

标签: mysql

我有3个人:

*** ps_currency

id      name
1       A
2       B
3       C
4       D

*** rate_sell

id_currency      RateSell
1                10
2                20

*** rate_buy

id_currency      RateBuy
2                25
3                30
4                40

如何选择输出

id      name     RateBuy       RateSell
1       A        NULL          10
2       B        25            20
3       C        30            NULL
4       D        40            NULL

谢谢,

1 个答案:

答案 0 :(得分:2)

  

从评论中复制粘贴
  我尝试了SELECT ps_currency。* FROM ps_currency LEFT JOIN rate_buy WHERE   rate_buy.id = ps_currency.id但它只显示id_currency RateSell 1   10 2 20

你需要使用带有ON子句的LEFT JOIN来使LEFT JOIN正常工作

<强>查询

 SELECT 
    ps_currency.id
  , ps_currency.name
  , rate_buy.RateBuy
  , rate_sell.RateSell
FROM 
  ps_currency

LEFT JOIN 
 rate_buy
ON
 ps_currency.id = rate_buy.id_currency

LEFT JOIN 
 rate_sell
ON 
  ps_currency.id = rate_sell.id_currency

ORDER BY
 ps_currency.id ASC

<强>结果

| id | name | RateBuy | RateSell |
|----|------|---------|----------|
|  1 |    A |  (null) |       10 |
|  2 |    B |      25 |       20 |
|  3 |    C |      30 |   (null) |
|  4 |    D |      40 |   (null) |

demo http://www.sqlfiddle.com/#!9/b0a23d/11