SQL-连接多个表

时间:2016-12-11 06:39:26

标签: sql sql-server database

我有3个SQL表:调制解调器,ModemsImage和ModemsPckg

    +----+-------+----------+
    | MID| Name  | Desc     |
    +----+-------+----------+
    | 1  |RNO-505|Wifi Modem|
    +-----------------------+

    +--- -+----+---------+
    | MIID| MID| ICON    |
    +-- --+----+---------+
    | 1   |1   |Cloud.png|
    +-- --+----+---------+
    | 2   |1   |Wire.png |
    +--------------------+

    +-----+--------+------------+-----+---+
    |MPKID|PckgName|PDesc       |Price|MID|
    +-----+--------+------------+-----+---+
    |1    |basic   |Starter Pckg|20.5 |1  |
    +-----+--------+------------+-----+---+
    |2    |Enhanced|advance pckg|66.5 |1  |
    +-------------------------------------+

我想要的最终结果:

    +----+-------+----------+-----+---------+-----+--------+------------+-----+
    | MID| Name  | Desc     | MIID| ICON    |MPKID|PckgName|PDesc       |Price|
    +-----------------------+-----+---------+-----+--------+------------+-----+
    | 1  |RNO-505|Wifi Modem| 1   |Cloud.png|1    |basic   |Starter Pckg|20.5 | 
    +-----------------------+-----+---------+-----+--------+------------+-----+
    | 1  |RNO-505|Wifi Modem| 2   |Wire.png |2    |Enhanced|advance pckg|66.5 | 
    +-------------------------------------------------------------------------+

我正在使用此查询:

select * from modems a join ModemsImage b on a.mid=b.mid join ModemsPckg c on a.mid=c.mid

但是这不会给我正确的输出,它返回的重复记录只是MPKID是不同的。 谢谢 编辑:: 当我使用时,此查询显示我完美的2条记录

    select c.MPKID from modems a join ModemsImage b on a.mid=b.mid join ModemsPckg c on a.mid=c.mid group by c.MPKID

但是当我试图检索更多列时,它就开始复制行。

2 个答案:

答案 0 :(得分:0)

  • 调制解调器有1行,其中MID = 1。
  • ModemsImage有2行,其中MID = 1。
  • ModemsPckg有2行,MID = 1。

您正在通过MID连接它们,以便获得:

  • Modems 1st row + ModemsImage 1st row + ModemsPckghave 1st row
  • Modems 1st row + ModemsImage 1st row + ModemsPckghave 2nd row
  • Modems 1st row + ModemsImage 2nd row + ModemsPckghave 1st row
  • Modems 1st row + ModemsImage 2nd row + ModemsPckghave 2nd row

为什么你会期待别的什么?

答案 1 :(得分:-1)

您需要在ModemsImage和ModemsPckg上添加其他条件。 例如:

select * from modems a 
INNER JOIN ModemsImage b on a.mid=b.mid 
INNER JOIN ModemsPckg c on a.mid=c.mid AND b.MIID=c.MPKID