【问题标题】:SQL Server working with 2 tables (foreign key?) ASP.NETSQL Server 使用 2 个表(外键?) ASP.NET
【发布时间】:2015-11-03 19:06:33
【问题描述】:

我的 SQL Server 数据库中有 2 个表,使用 Visual Studio 2013:

  1. 类别

    • 身份证
    • 姓名
  2. 产品

    • 身份证
    • 姓名
    • 类别 ID

我有一个在 ASP.NET(网络表单)中构建的产品页面,我可以在其中创建、编辑或删除产品。

我在两个表之间建立了连接(外键)。

我想展示我的产品,而不是将类别作为数字 (Id) 我想拥有它的名称。

我该怎么做?

我的 SQL 知识非常基础。

这就是我使用 DataList 显示代码的方式:

string SQL = "SELECT * FROM Products;";
SqlCommand cmd = new SqlCommand(SQL, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);

dlProducts.DataSource = ds;
dlProducts.DataBind();

非常感谢!!

【问题讨论】:

    标签: asp.net sql-server foreign-keys


    【解决方案1】:

    加入类别表,并从类别表中返回名称以及主要结果。

    string SQL = "SELECT p.*, pc.Name FROM Products p
                  INNER JOIN ProductCategories pc
                  ON p.ProductCategoryID = pc.ProductCategoryID;";
    

    【讨论】:

    • 我要感谢你们所有人!真的非常感谢!!
    【解决方案2】:

    您正在寻找join

    您的查询可能如下所示:

    select *
    from products p -- p is an "alias" for the table products
    inner join category c on p.categoryId = c.id -- here we're specifying that the products table to join onto the category table via their relationship columns.
    

    请注意,上述内容将返回比您需要的更多的列,您可以将* 更改为仅返回所需的列(通常认为指定列列表更好)

    【讨论】:

      【解决方案3】:

      将您的选择语句更改为:

      "SELECT p.Id, p.Name, c.Name FROM Product p, Category c WHERE p.CategoryId=c.Id;"
      

      【讨论】:

      • 虽然这看起来在技术上可行,但我相信逗号“连接”通常不受欢迎,因为它们是一种较旧的语法且效率低下。请参阅stackoverflow.com/a/129410/2312877 了解更多信息。虽然也有一些关于它的无效率的争论:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 2011-03-11
      • 2014-01-24
      相关资源
      最近更新 更多