2016-06-21 57 views
2

我想從Products表中獲取產品名稱到CustomerProducts表。在sql數據庫中加入2個表或外鍵?

Products表:

Products

customerproducts表:

customerproducts

UPDATE:

public void bindgrid() 
    { 
     SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"); 
     SqlCommand cmd = new SqlCommand("select Name From Products p InnerJoin CustomerProducts cp ON(p.ProductID = cp.ProductID)", conn); 

     SqlDataAdapter da = new SqlDataAdapter("", conn); 
     da.SelectCommand = new SqlCommand("select ProductName From Products p InnerJoin CustomerProducts cp ON(p.ProductID = cp.ProductID", conn); 
     DataSet ds = new DataSet(); 
     da.Fill(ds, "data"); 
     GridView1.DataSource = ds.Tables[0].DefaultView; 
     GridView1.DataBind(); 
    } 
+0

的鏈接不工作。 –

+2

內部連接和外部鍵是用於不同目的的不同工具。你的問題就像問摩托車或菜刀。請做一些研究。 –

+0

使用該表格數據,預期的結果是什麼? – jarlh

回答

2

如果你想把它當作一個選擇:

SELECT cp.customerID,cp.productID,p.name 
FROM products p 
INNER JOIN customerProducts cp 
ON(p.productID = cp.productID) 

如果你想添加一列第二表來,首先添加列,然後更新:

UPDATE customerProducts cp 
SET cp.name = (SELECT p.name FROM products p 
       WHERE p.productID = cp.productID) 
+0

請參閱更新先生。 –

+0

我的查詢有什麼問題?更新後我沒有看到任何新問題。 – sagi

+0

給了我一個錯誤sir''InnerJoin'附近的語法不正確。' –