在sql数据库中使用2个表或外键进行内连接?

时间:2016-06-21 11:44:12

标签: sql foreign-keys inner-join

我想从Products表到CustomerProducts表获取产品名称。

Products表:

Products

customerproducts表:

customerproducts

更新:

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();
    }

1 个答案:

答案 0 :(得分: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)