你能帮我加入3个表并制作外键

时间:2016-01-09 08:40:30

标签: sql sql-server foreign-keys

我有3张桌子

  1. Table 1:ID_Customer char(10),Name varchar(50)
  2. Table 2:ID_Bill Char(10),Status varchar(50), ID_Customer char(10).FK,ID_Offer char(10)FK
  3. Table 3:ID_Offer char(10),包varchar(50), ID_Customer char(10).FK
  4. 我想要那个3关系并拥有外键,如果我加入3个表就可以看到像这样的数据

    ID_Customer|Name|ID_Bill|Status|ID_Offer|Package  | 
    -----------+----+-------+------+--------+---------+
    C001       |Ang |BI001  |Paid  |OF001   |Package A|
    

    该数据可以查看表格和内容中的数据。

2 个答案:

答案 0 :(得分:2)

SELECT t1.ID_Customer,
       t1.Name,
       t2.ID_Bill,
       t2.Status,
       t3.ID_Offer,
       t3.Package
FROM   table1 t1
       INNER JOIN table2 t2
               ON t1.ID_Customer = t2.ID_Customer
       INNER JOIN table3 t3
               ON t2.ID_Offer = t3.ID_Offer 

答案 1 :(得分:2)

这是一个非常简单的SQL基础知识101加入.....

SELECT
    c.ID_Customer, c.Name, b.ID_Bill, b.Status, o.ID_Offer, o.Package
FROM
    dbo.Customer c  -- "table 1"
INNER JOIN
    dbo.Bill b ON b.ID_Customer = c.ID_Customer   -- "table 2"
INNER JOIN
    dbo.Order o ON o.ID_Customer = c.ID_Customer  -- "table 3"